Testing for a file in python?

Moshe Zadka moshez at math.huji.ac.il
Tue Jun 13 00:33:06 EDT 2000


On Mon, 12 Jun 2000, A[r]TA wrote:

> > How would you go about testing if a certain file exists in python?
> > In most scripting languages you have the -f test:
> >
> > if -f filename do
> >    whatever_you_were_going_to_do
> >    fi
> > else do
> >    print "Error" file not found
> >    fi
> >
> > stat doesn't work, it aborts if the file does not exist.
> 
> try:
>     open('filename')
> except:
>     print 'File does not exist'

1. This checks that the file is readable too, which wasn't what the
original poster wanted.

2. Unqualified "except"s are evil. Use except (IOError, os.error): in this
case.

3. You're relying on GC to free the file descriptor, which is a dangerous
assumption (doesn't work on JPython, for example)

--
Moshe Zadka <moshez at math.huji.ac.il>
http://www.oreilly.com/news/prescod_0300.html
http://www.linux.org.il -- we put the penguin in .com





More information about the Python-list mailing list