Python Forum
How to search full path of specified file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to search full path of specified file
#1
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")
Reply
#2
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")
Reply
#3
I use argparse. a prefix (root directory) is an argument, and post_fix is hard-coded purposely. So, I still can use pathlib?
Reply
#4
Yes you can use pathlib by converting the argument into a Path
directory = Path(argument)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Search Excel File with a list of values huzzug 4 1,147 Nov-03-2023, 05:35 PM
Last Post: huzzug
  Search for multiple unknown 3 (2) Byte combinations in a file. lastyle 7 1,256 Aug-14-2023, 02:28 AM
Last Post: deanhystad
  File path by adding various variables Mishal0488 2 963 Apr-28-2023, 07:17 PM
Last Post: deanhystad
  search file by regex SamLiu 1 860 Feb-23-2023, 01:19 PM
Last Post: deanhystad
  Script File Failure-Path Error? jerryf 13 3,313 Nov-30-2022, 09:58 AM
Last Post: jerryf
  If function is false search next file mattbatt84 2 1,111 Sep-04-2022, 01:56 PM
Last Post: deanhystad
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,148 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  fuzzywuzzy search string in text file marfer 9 4,424 Aug-03-2021, 02:41 AM
Last Post: deanhystad
  Cloning a directory and using a .CSV file as a reference to search and replace bg25lam 2 2,100 May-31-2021, 07:00 AM
Last Post: bowlofred
  Subprocess.Popen() not working when reading file path from csv file herwin 13 14,615 May-07-2021, 03:26 PM
Last Post: herwin

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020