[Tutor] IOError exception handling

Allyn Weaks allyn@tardigrade.net
Sat, 27 Jul 2002 15:19:13 -0700


Unix; linux 7.1 if it matters.  Can one get a more finely divided error
back than IOError?  I'm counting lines in files that may or may not
exist, and if one doesn't exist, I can set the number of lines to zero
and continue with the rest.  But, if the file can't be opened because
of any other problem, such as a permission error, I want it to bail
with whatever error message is appropriate (preferably without handling
each and every case at this point, since I'm still a first instar
pythonista...)

def countlines(filename):
	try:
		f = open(filename, 'r')
		text = f.readlines()
		f.close()
		return len(text)
	except (file doesn't exist):
		return 0

Many thanks!
-- 
Allyn Weaks    allyn@tardigrade.net   Seattle, WA  Sunset zone 5
Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/
"The benefit of even limited monopolies is too doubtful, to be opposed
to that of their general suppression."  Thomas Jefferson