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

4

7

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.

Cuspidate answered 20/2, 2013 at 22:9 Comment(4)
What do you want to do with the file? Overwrite it? Read it? Append to it? Both?Offal
"When I try and make the file it won't work (I think because python has to generate it)." Hardly so. You should add more details and show the relevant code you have.Hoofed
The file needs to exist that is allCuspidate
The application likely cannot find KEEP-IMPORTANT.txt because the current working directory for the application is different from what you expect. The default working directory is <application>.app/Contents/Resources. If the file is a read-only data file you could copy it into the application bundle (py2app has an option for that)Heisler
M
8

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.

Monoicous answered 20/2, 2013 at 22:16 Comment(4)
I contrived an example to test this method for flaws. In python 2.7 permission errors raise IOError. I revoked read access for a test file but allowed write. Trying to read the file produced an IOError and I was able to overwrite it using this exception. This will not work in python 3 as reading the file produces PermissionError. This is probably a niche scenario that is unlikely to happen. I wonder what other ways IOError could occur with an existing file.Stepaniestepbrother
If you don't have rw permissions for the file, won't trying to clobber it just raise another IOError?Monoicous
In python 3 it would raise PermissionError. I tested the unlikely scenario that you had write permissions but not read permissions. In this case, for python 2.7, reading the file raised IOError but I could still write to it with write permissions.Stepaniestepbrother
This answer introduces a race condition -- it's possible for the file to have been created by another process between the time you try to open it and the time you try to create it. The right answer is to open the file with the right options to control write, append, truncate etc.Cohesion
R
11

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

open("KEEP-IMPORTANT.txt", "a")
Roommate answered 20/2, 2013 at 22:19 Comment(2)
+1 for it making the file and no errors - but what about also deleting previous bits of the file?Giotto
@Giotto Change the mode to "w" (write). Will overwrite the existing contents.Foreordain
M
8

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.

Monoicous answered 20/2, 2013 at 22:16 Comment(4)
I contrived an example to test this method for flaws. In python 2.7 permission errors raise IOError. I revoked read access for a test file but allowed write. Trying to read the file produced an IOError and I was able to overwrite it using this exception. This will not work in python 3 as reading the file produces PermissionError. This is probably a niche scenario that is unlikely to happen. I wonder what other ways IOError could occur with an existing file.Stepaniestepbrother
If you don't have rw permissions for the file, won't trying to clobber it just raise another IOError?Monoicous
In python 3 it would raise PermissionError. I tested the unlikely scenario that you had write permissions but not read permissions. In this case, for python 2.7, reading the file raised IOError but I could still write to it with write permissions.Stepaniestepbrother
This answer introduces a race condition -- it's possible for the file to have been created by another process between the time you try to open it and the time you try to create it. The right answer is to open the file with the right options to control write, append, truncate etc.Cohesion
E
1
import os.path
from os import path
    if path.exists('highScore.txt'):
         print("It exists")
    else:
         print("It doesn't exist")

Eloign answered 12/12, 2019 at 0:54 Comment(0)
W
1

Another clean and small solution if you want to check and create the file only with out writing anything right away would be this.

import os
if os.path.exists(file_path) == False:
    open(file_path, "w").close
Welterweight answered 27/3, 2020 at 18:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.