Very new to Python here. I am trying to read a file from a folder, but without knowing its full name. For example AAA_05212021.csv
is the file name located in C:\test\
AAA is the known part of the file name. The rest changes everyday.
I tried:
import pandas as pd
data = pd.read_csv(r'C:\test\AAA*.csv')
.. but it doesn't seem to work. Any help would be much appreciated. Thanks!
You can use glob for this. Glob will return a list of files that match the pattern. Since, there is only one file that matches the pattern in the directory, you can get it with the index 0
:
from glob import glob
import pandas as pd
file = glob('C:\test\AAA*.csv')[0]
data = pd.read_csv(file)
This code should identify all of the possible files it could be:
import os
valid_files = []
for file in os.listdir('C:\test'):
# Check that "AAA" is in the filename
if "AAA" in file:
# Check that "AAA" is at the start of the filename
if file.partition("AAA")[0] == "":
valid_files.append(file)
Of course, if there are multiple files in the folder that follow that structure, you'll still need to pick one somehow, but that could be as simple as files[0]
if you aren't picky.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.