How does Python handle probing to see if a file already exist s?

sismex01 at hebmex.com sismex01 at hebmex.com
Tue Nov 5 09:51:13 EST 2002


> From: Christopher R. Culver [mailto:Kricxjo.neniuspamajxo at yahoo.com]
> 
> Hello all,
> 
> I've just begun learning Python after already getting pretty 
> proficient in C. However, I'm having a problem with a simple
> copying program. Ideally, the program would check to see if
> the destination already exists and prompt the user. In this
> this would be as easy as saying:
> 
> probe_destination = fopen(/usr/bin/foo, 'r')
> if (probe_destination)
> {
> some code here;
> }
> 
> However, translating that directly into Python doesn't work because
> if Python can't find a file to open, it doesn't just return 0, it
> gives an error and exits. How can I write this functionality in Python 
> so that it returns 0 and continues, or does Python have a totally 
> different way of handling this problem than C?
> 
> Christopher Culver
>

Others have talked about the goodness of using try/except, I'll
say to use os.access(), which is precisely for what you're asking,
if you can read or write a file.

-- check if writeable --

import os
if os.access("some-filename", os.W_OK):
   # neat, I can write to the file.
   ...

-- check if readable --

import os
if os.access("some-filename", os.R_OK):
   # OK, I can read from the file.
   ...

-- check if executable --

import os
if os.access("some-filename", os.X_OK):
   # OK, I can execute this file.
   ...

-- check existance --

import os
if os.access("some-filename", os.F_OK):
   # File exists, but I don't know what I can do with it.
   ...


You can do a bitwise OR on the flags R_OK, W_OK and X_OK to
check combined permissions, R_OK|W_OK would check for read
and write permission on the same file.

Exception handling is neat and all, but sometimes it just isn't
the right way to only check for some condition.  I mean, you
don't blindly walk into a door to see if it's locked or not.

:-)

-gustavo





More information about the Python-list mailing list