How to have Python check if a file exists and create it if it doesn't?

user2093174 picture user2093174 · Feb 20, 2013 · Viewed 21.3k times · Source

How to have Python look and see if there is a file it needs and if there isn't create one?

Basically I want Python to look for my file name KEEP-IMPORTANT.txt, but when I create my app using py2app it doesn't work because it doesn't have the file. When I try and make the file it won't work (I think because python has to generate it).

I want Python to check if the file exists so that if it does then it doesn't generate the file, otherwise it does.

Answer

Robᵩ picture Robᵩ · Feb 20, 2013

This one-liner will check to see if the file exists, and create it if it doesn't.

open("KEEP-IMPORTANT.txt", "a")