How to check Python if a file exists and create it if it is not?

How to get Python and see if there is a file that it needs, and if not create it?

Basically, I want Python to look for the name of my file KEEP-IMPORTANT.txt , but when I create my application using py2app , it does not work because it does not have a file. When I try to make a file, it will not work (I think because python should generate it).

I want Python to check if the file exists so that if it does, it does not generate the file, otherwise it does.

+6
source share
2 answers

Similar question

This is the best way:

 try: with open(filename) as file: # do whatever except IOError: # generate the file 

There is also os.path.exists (), but this can be a security issue.

+7
source

This single line file checks to see if the file exists and create it if it is not.

 open("KEEP-IMPORTANT.txt", "a") 
+7
source

All Articles