Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 602
user2093174 Avatar asked Feb 20 '13 22:02

user2093174


2 Answers

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

open("KEEP-IMPORTANT.txt", "a")
like image 82
Robᵩ Avatar answered Oct 21 '22 20:10

Robᵩ


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.

like image 41
Alex Hammel Avatar answered Oct 21 '22 22:10

Alex Hammel