Python about file I/O

Erik Max Francis max at
Fri Sep 20 23:30:08 EDT 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:

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

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

More information about the Python-list mailing list