Which is the preferred way to check if a file exists and if not create it?
To check if a path is an existing file:
Trueif path is an existing regular file. This follows symbolic links, so both
isfile()can be true for the same path.
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.
if not os.path.exists(filename): 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.