best way to check if a file exists?

wittempj@hotmail.com martin.witte at gmail.com
Wed Nov 1 07:15:48 EST 2006


John Salerno 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.
>
> Thanks.

You could try to read the file, if that fails it doesn't exist:

try:
    f = open('xxx')
except IOError:
    f = open('xxx', 'w')
    print "file doesn't exist"
print f




More information about the Python-list mailing list