[Tutor] file?

David Rock david at graniteweb.com
Tue Apr 4 05:26:06 CEST 2006

* kakada <hokkakada at khmeros.info> [2006-04-04 09:32]:
> Hi all,
> How can we know that one specific file is already exist in filesystem?
> for instance, I want to read zipfile by issuing code:
> import zipfile
> ziparchive = zipfile.ZipFile(inputfilename, "r")
> if the inputfilename doesn't exist then an error would be occurred.
> I want to catch up this special case first.

The key here is to actually "catch" the exception.  Python is very good
at assuming something will work, and then deal only with the exceptions:

import zipfile

	ziparchive = zipfile.ZipFile(inputfilename, "r")
	print "error accessing file"

You could get fancy and deal with various exceptions or read traceback
info, too.  Using the try block is generally considered a more Pythonic
way of handling the problem. :-)

David Rock
david at graniteweb.com

More information about the Tutor mailing list