0

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?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
sam_sam
  • 449
  • 1
  • 5
  • 16
  • What's does `file2` end up as after concatenation? (by the way you're missing the closing apostrophe) – half of a glazier Apr 22 '21 at 12:33
  • 2
    To find files using wildcards you should look at using glob - https://docs.python.org/3/library/glob.html. – norie Apr 22 '21 at 12:35
  • Does this answer your question? [Get a filtered list of files in a directory](https://stackoverflow.com/questions/2225564/get-a-filtered-list-of-files-in-a-directory) – Tomerikoo Apr 22 '21 at 12:41

4 Answers4

1

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]
0

you can use glob module:

import glob
file2 = glob.glob(file2)[0]
Amit Nanaware
  • 3,203
  • 1
  • 6
  • 19
0
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

Eeshaan
  • 1,557
  • 1
  • 10
  • 22
0

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.

Minh Quân
  • 36
  • 4