best way to check if a file exists?

georgeryoung at gmail.com georgeryoung at gmail.com
Tue Oct 31 19:56:30 EST 2006


On Oct 31, 4:01 pm, John Salerno <johnj... at NOSPAMgmail.com> wrote:
> What is the best way to check if a file already exists in the current
> directory? I saw os.path.isfile(), but I'm not sure if that does more
> than what I need.
>
> I just want to check if a file of a certain name exists before the user
> creates a new file of that name.

You could be more "pythonic", and simply try to create the file,
catching the exception if if fails.  This works on linux:

try:
   newfd = os.open('foobar', os.O_EXCL | os.O_CREAT)
   new_file = os.fdopen(newdf)
except OSError, x:
   if x[1] == 'File exists':
      handle_file_exists()

[but beware unreliable on an NFS file system, from "man open":
   O_EXCL is broken  on  NFS  file
   systems,  programs  which  rely  on it for performing locking tasks
   will contain a race condition.  The solution for performing  atomic
   file  locking  using  a  lockfile is to create a unique file on the
   same fs (e.g., incorporating hostname and pid), use link(2) to make
   a  link  to the lockfile. If link() returns 0, the lock is
successful.­
   Otherwise, use stat(2) on the unique file  to  check  if  its
   link  count has increased to 2, in which case the lock is also
suc­cessful.]




More information about the Python-list mailing list