12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

138 Chapter 14. FilesTodemonstratethesefunctions,thefollowingexample“walks”throughadirectory,printsthenamesof all thefiles, and calls itselfrecursively on allthe directories.def walk(dir):for name in os.listdir(dir):path = os.path.join(dir, name)if os.path.isfile(path):print pathelse:walk(path)os.path.jointakes adirectory and afile name and joins them intoacomplete path.Exercise 14.1 Modify walk so that instead of printing the names of the files, it returns a list ofnames.Exercise 14.2 The os module provides a function called walk that is similar to this one but moreversatile. Read the documentation and use it to print the names of the files in a given directory anditssubdirectories.14.5 CatchingexceptionsA lot of things can go wrong when you try to read and write files. If you try to open a file thatdoesn’t exist, you get anIOError:>>> fin = open('bad_file')IOError: [Errno 2] No such file or directory: 'bad_file'Ifyou don’t have permissiontoaccess afile:>>> fout = open('/etc/passwd', 'w')IOError: [Errno 13] Permission denied: '/etc/passwd'And ifyou trytoopen a directoryfor reading, you get>>> fin = open('/home')IOError: [Errno 21] Is a directoryTo avoid these errors, you could use functions like os.path.exists and os.path.isfile, but itwould take a lot of time and code to check all the possibilities (if “Errno 21” is any indication,there areat least 21things that can go wrong).Itisbettertogoaheadandtry,anddealwithproblemsiftheyhappen,whichisexactlywhatthetrystatement does. The syntax issimilartoanifstatement:try:fin = open('bad_file')for line in fin:print linefin.close()except:print 'Something went wrong.'

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!