Python Forum

Full Version: search and read file given partial file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
this is where functions come in.
def read_file(filaneme):
    with open(filename) as fp:
        for line in fp:
            fp.strip()
            ...
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)