1

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!

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.