Reputation: 469
I have a folder with many .csv files in it with the following format:
FGS07_NAV_26246_20210422_86oylt.xls
FGS07_NAV_26246_
is always the same, 20210422
is the date and the most important parameter to go and pick the file, _86oylt
also changes but not important at all.
I need to read one csv file with the same date as the operation date.
let’s think that y
is our date part, so I tried this code, but it doesn’t give me the write name:
file2 = r'C:/Users/name/Finance/LOF_PnL/FGS07_NAV_26246_' + y + '*.xls'
df2 = pd.read_excel(file2)
How should I fix?
Upvotes: 0
Views: 1474
Reputation: 46
if you want just the specific file, you could try this one:
xls_file = [file for file in os.listdir(r"C:/Users/name/Finance/LOF_PnL") if file.endswith("xls") and y in file][0]
Upvotes: 1
Reputation: 36
Maybe you can try to use join() or os.path.join() which are more standard.
"".join([str1, str2])
os.path.join(path_to_file, filename)
I hope this could be helpful. Maybe check the type of the file again also.
Upvotes: 0
Reputation: 1635
import os
all_files = os.listdir(r'C:/Users/name/Finance/LOF_PnL')
filtered_files = list(filter(lambda x : 'FGS07_NAV_26246_' + y in x, all_files))
and now filtered_files
is a list with the names of all files having 'FGS07_NAV_26246_' + y
in their file names. You can add the full path to these names if you want the absolute path. You can also use regex for a more fancy pattern lookup than in
Upvotes: 0
Reputation: 3346
you can use glob
module:
import glob
file2 = glob.glob(file2)[0]
Upvotes: 0