Reputation: 1533
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.
Upvotes: 0
Views: 207
Reputation: 2047
import pathlib
file_PATH = pathlib.Path('y:/file_A.txt')
if file_PATH.is_file():
file_to_use = "y:/file_A.txt"
else:
file_to_use = "d:/file_B.txt"
EDIT: due to comment about Python 3.4
You can do it with os.path.exists with Python 2:
>>> import os.path
>>> file_path = 'c:/file_false.txt'
>>> os.path.exists(file_path)
False
>>> file_path = 'c:/file_real.txt'
os.path.exists(file_path)
True
So
import os.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"
Upvotes: 1
Reputation: 7819
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"
Upvotes: 1
Reputation: 3170
I would suggest that you check for the existence of the file.
In python 3.4 : the pathlib module offers an object-oriented approach-:
from pathlib import Path
if Path(r"/path/to/file_A.txt").is_file():
file_to_use = "y:/file_A.txt"
elif Path(r"/path/to/file_B.txt").is_file():
file_to_use = "d:/file_B.txt"
else:
# Do something if both files don't exist
Upvotes: 0