[Tutor] Equivalent exception of os.path.exists()

Sander Sweers sander.sweers at gmail.com
Mon Nov 30 22:14:54 CET 2009

2009/11/30 biboy mendz <bibsmendez at gmail.com>:
> clause, it should be on the fobj-open line. But im still looking for the
> exception that will be raised when i input a filename and that file already
> exists. I hope you get what i mean :-)

There is no exception to alert you a file already exists. Depending on
how you open the file (mode) it will either read, write or append to
the file. If the file exists and you open it in write mode it *will*
overwrite the file. See [1] for more info.

So what you need to do is check yourself if the file exists and make
the python script take appriate action. For example:

import os
fname = "C:\\testfile.txt"
if os.path.exists(fname):
    do something if exists
   do something else if not exists


[1] http://docs.python.org/library/functions.html#open

More information about the Tutor mailing list