Python Forum

Full Version: How to search full path of specified file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I am trying to search a full path of the file given a root directory (this can vary), and postfix file name.
I am using the below code but I always get File does not exist ad list index out of range. and my full file path is empty.


#%%
import glob
import sys
import os
file1_name = "D:\Backupdata"
post_fix = ["\PythonCodes\InputCSV1.csv"]

try:
    full_path = (glob.glob(file1_name + str(post_fix)))[0]
    if (os.path.exists(full_path == True)):
        print("file exists")
    else:
        print("fail")
except FileNotFoundError or IndexError:
    print("file does not exist")
Why not use the user-friendly pathlib module from the standard library ?
from pathlib import Path

file1_name = Path("D:") / "Backupdata"
post_fix = Path() / "PythonCodes" / "InputCSV1.csv"

if (file1_name / post_fix).isfile():
    print("File exists")
else:
    print("No such file")
I use argparse. a prefix (root directory) is an argument, and post_fix is hard-coded purposely. So, I still can use pathlib?
Yes you can use pathlib by converting the argument into a Path
directory = Path(argument)