Python about file I/O

Erik Max Francis max at alcyone.com
Sat Sep 21 05:30:08 CEST 2002


Ken wrote:

> 1.) How do you list the filenames within a given directory so user can
> choose which file to open?

Use os.listdir.

> 2.) How do you ensure the program doesn't crash if I specify a
> filename to
> open but the file doesn't exist? (I.E. how to check if file exist
> before
> opening the file?)

It doesn't "crash," it throws an error.  Simply catch the error and do
something meaningful:

	try:
	    inFile = file('soandso.txt')
	    ...
	except IOError:
	    print >> sys.stderr, "Couldn't open file"

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Woman was God's _second_ mistake.
\__/ Friedrich Nietzsche
    The laws list / http://www.alcyone.com/max/physics/laws/
 Laws, rules, principles, effects, paradoxes, etc. in physics.



More information about the Python-list mailing list