Python Forum
search and read file given partial file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
search and read file given partial file
#1
Hi,
I want to read file given a partial file name:

import glob
my_dir = 'D:\PythonCodes'
#post_fix = ['\InputFiles\KYLJHQ_20191215\sub_folder/InputCSV.csv','\InputFiles\KYLJHQ_20191215\sub_folder/InputCSV2.csv']
post_fix = ['\InputFiles\KYLJHQ_*\sub_folder/InputCSV.csv','\InputFiles\KYLJHQ_*\sub_folder/InputCSV2.csv']


for i in range(len(post_fix)):
    full_path = glob.glob(my_dir + str(post_fix[i]))
    tmp_file = open(full_path,'r')
    tmp_data = tmp.readlines()
    print(tmp_data)
the file structure is D:\PythonCodes -->\InputFiles\KYLJHQ_*\sub_folder/InputCSV.csv. I uae above code but it giving error:

TypeError: expected str, bytes or os.PathLike object, not list
Reply
#2
this is where functions come in.
def read_file(filaneme):
    with open(filename) as fp:
        for line in fp:
            fp.strip()
            ...
Reply
#3
You give a list to open in line 9.
Some point you don't need glob as you construct a full path here,and use join to join paths.
So if put it together and use also code from Larz.
from os.path import join

def read_file(filename):
    with open(filename) as fp:
        for line in fp:
            print(line.strip())

# No \ singel in path,eg use raw string
my_dir = r'D:\PythonCodes'
post_fix = ['InputFiles\KYLJHQ_*\sub_folder\InputCSV.csv', 'InputFiles\KYLJHQ_*\sub_folder\InputCSV2.csv']
full_path = []
for r_path in post_fix:
    full_path.append(join(my_dir, r_path))

# Now read both files
for path in full_path:
    read_file(path)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  partial functions before knowing the values mikisDeWitte 4 589 Dec-24-2023, 10:00 AM
Last Post: perfringo
  file open "file not found error" shanoger 8 1,065 Dec-14-2023, 08:03 AM
Last Post: shanoger
  Recommended way to read/create PDF file? Winfried 3 2,855 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,407 Nov-09-2023, 10:56 AM
Last Post: mg24
  Search Excel File with a list of values huzzug 4 1,211 Nov-03-2023, 05:35 PM
Last Post: huzzug
  Move Files based on partial Match mohamedsalih12 2 802 Sep-20-2023, 07:38 PM
Last Post: snippsat
  Need to replace a string with a file (HTML file) tester_V 1 751 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Search for multiple unknown 3 (2) Byte combinations in a file. lastyle 7 1,307 Aug-14-2023, 02:28 AM
Last Post: deanhystad
  How can I change the uuid name of a file to his original file? MaddoxMB 2 912 Jul-17-2023, 10:15 PM
Last Post: Pedroski55
  read file txt on my pc to telegram bot api Tupa 0 1,092 Jul-06-2023, 01:52 AM
Last Post: Tupa

Forum Jump:

User Panel Messages

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