Pythonic way to check if a file exists?


Question

Which is the preferred way to check if a file exists and if not create it?

1
180
2/13/2010 10:42:35 PM

Accepted Answer

To check if a path is an existing file:

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

262
2/13/2010 10:59:01 PM

Instead of os.path.isfile, suggested by others, I suggest using os.path.exists, which checks for anything with that name, not just whether it is a regular file.

Thus:

if not os.path.exists(filename):
    file(filename, 'w').close()

Alternatively:

file(filename, 'w+').close()

The latter will create the file if it exists, but not otherwise. It will, however, fail if the file exists, but you don't have permission to write to it. That's why I prefer the first solution.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon