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
  [fixed] distinguish file name from the path paul18fr 5 126 Feb-13-2026, 02:49 PM
Last Post: DeaD_EyE
  How to read a file as binary or hex "string" so that I can do regex search? tatahuft 3 2,972 Dec-19-2024, 11:57 AM
Last Post: snippsat
  Search in a file using regular expressions ADELE80 2 2,036 Dec-18-2024, 12:29 PM
Last Post: ADELE80
  import a function from another file using relative path paul18fr 6 10,448 Aug-01-2024, 06:40 AM
Last Post: paul18fr
  Search Excel File with a list of values huzzug 4 5,059 Nov-03-2023, 05:35 PM
Last Post: huzzug
  Search for multiple unknown 3 (2) Byte combinations in a file. lastyle 7 4,562 Aug-14-2023, 02:28 AM
Last Post: deanhystad
  File path by adding various variables Mishal0488 2 6,595 Apr-28-2023, 07:17 PM
Last Post: deanhystad
  search file by regex SamLiu 1 2,188 Feb-23-2023, 01:19 PM
Last Post: deanhystad
  Script File Failure-Path Error? jerryf 13 13,579 Nov-30-2022, 09:58 AM
Last Post: jerryf
  If function is false search next file mattbatt84 2 2,523 Sep-04-2022, 01:56 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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