[Tutor] Does directory exist?
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Thu Apr 3 15:02:01 2003
On Thu, 3 Apr 2003, Michael Montagne wrote:
> What is the best way to check for the existence of a directory? I used
> os.stat() in a try:except: statement. It seems the os.access() function
> is intended for this but I can't get it to accept F_OK as the mode
> argument.
Hi Michael,
There are a set of convenience functions in the 'os.path' subpackage; we
can check it out here:
http://www.python.org/doc/lib/module-os.path.html
In particular, os.path.exists() is probably what you're looking for.
Here's a sample of how to use it:
###
>>> import os.path
>>> os.path.exists('/etc/passwd')
1
>>> os.path.exists('/etc')
1
>>> os.path.exists('/foobar')
0
###
So os.path.exists() works well with both files and directories.
Using the os.path module allows us to concentrate on common path-related
tasks without having to worry about flags like 'F_OK'.