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

Martin v. Löwis loewis at informatik.hu-berlin.de
Tue Nov 5 05:53:36 EST 2002


"Christopher R. Culver" <Kricxjo.neniuspamajxo at yahoo.com> writes:

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

The set of error conditions is nearly identical between C and Python,
as Python adds only a thin wrapper around the C library.

However, the way in which errors are reported to the program is
completely different: C uses return values and implicitly-changing
global variables (errno); Python uses exceptions. In the specific
case, what you see is the IOError exception. If it is not caught, it
causes a program exit, with an error message (which we call
'traceback').

If you expect certain errors to happen, you can prepare for that in
the program:

try:
    f = open('/usr/bin/foo','r')
except IOError:
    some code here

There are variations to this try-except statement, see

http://www.python.org/doc/current/ref/try.html

In this case, the most common variations would be

try:
    f = open('/usr/bin/foo','r')
except IOError, exc:
    if exc.ENOENT:
        # expecting that the file does not exist
        some code here
    else:
        # some unexpected error: re-raise
        raise

if you want to process only a single case of IOError, and

try:
    f = open('/usr/bin/foo','r')
except IOError:
    some code here, f is still unassigned
else:
    normal processing, can use f.

if you can execute the normal processing only if opening succeeded.

Regards,
Martin



More information about the Python-list mailing list