How to have Python check if a file exists and create it if it doesn't?
This one-liner will check to see if the file exists, and create it if it doesn't.
open("KEEP-IMPORTANT.txt", "a")
Similar question
This is the best way:
try:
with open(filename) as file:
# do whatever
except IOError:
# generate the file
There's also os.path.exists(), but this can be a security concern.