Stefan Stefan - 1 month ago 9
Python Question

Use another file A if file B does not exist

I think it is a simple task. I tried a lot of things with no success.

I want to use a file A on a network directory and when I'm offline I want to use file B on my ssd.

file_PATH = "y:/file_A.txt"

if os.path.isfile(file_PATH):
file_to_use = "y:/file_A.txt"
else:
file_to_use = "d:/file_B.txt"


It doesn't work with this piece of code.
When I rename file_A for testing, file_B will not be used.

UPDATE

I've found the (very silly) mistake. It was a misspelling of one of the two directories.

Answer

Use os.path.exists and also think about using os.path.join for building your path.

file_PATH = "y:/file_A.txt"

if os.path.exists(file_PATH):
    file_to_use = "y:/file_A.txt"
else:
    file_to_use = "d:/file_B.txt"
Comments