file existence checking
Fredrik Lundh
fredrik at pythonware.com
Wed Feb 15 09:48:14 EST 2006
"john peter" <neuzhoundxx at yahoo.com> wrote:
> does anyone have a suggestion on simplest way to check for the existence of a file
> within the same directory where a python script was started without really opening
> it?
it's not like opening a file is a very expensive or dangerous operation, but
you can use
import os
if os.path.isfile(filename):
print "a file named", filename, "exists"
or
if os.path.exists(filename):
print "something named", filename, "exists"
to check for a file. however, if you plan to open the file later on, it's better
to just open it, and deal with the exception; e.g.
try:
f = open(filename)
except IOError:
print "failed to open", filename
sys.exit(1)
data = f.read(100)
</F>
More information about the Python-list
mailing list