Search code examples
pythonfilepython-3.xpy2app

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.


Solution

  • 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.