Python Forum
How to search full path of specified file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to search full path of specified file (/thread-23176.html)



How to search full path of specified file - SriRajesh - Dec-14-2019

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")



RE: How to search full path of specified file - Gribouillis - Dec-14-2019

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")



RE: How to search full path of specified file - SriRajesh - Dec-14-2019

I use argparse. a prefix (root directory) is an argument, and post_fix is hard-coded purposely. So, I still can use pathlib?


RE: How to search full path of specified file - Gribouillis - Dec-14-2019

Yes you can use pathlib by converting the argument into a Path
directory = Path(argument)