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

Gerhard Häring gerhard.haering at opus-gmbh.net
Tue Nov 5 05:50:48 EST 2002


In article <pan.2002.11.05.10.28.55.506357 at yahoo.com>, Christopher R. Culver wrote:
> 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.

Yes, Python does have exception handling, which is a very useful thing. You
just have to decide what to do in the error case, for example:

try:
    f = open("/usr/bin/foo")
    # some code here
except IOError, reason:
    print "couldn't open file, because of", reason 

> 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?

In Python, you catch the exception and decide what to do with it (if anything).
If, for example, you just want to ignore the IOError (but not other errors),
you'd simply do:

try:
    f = open("/usr/bin/foo")
    # some code here
except IOError:
    pass

It's also possible to check if a file exists before trying to open it:

if os.path.exists("/usr/bin/foo"):
    # more code here

But the existence of the file does not guarantee you have the necessary
permissions to actually open it. It could also be deleted in the millisecond or
so between your check and trying to open it. Or some other problem could occur.
That's why using exceptions and catching the IOError is the only practical way
if you want to produce robust code.
-- 
Gerhard Häring
OPUS GmbH München
Tel.: +49 89 - 889 49 7 - 32
http://www.opus-gmbh.net/



More information about the Python-list mailing list