读取没有全名的 CSV 文件

Reading a CSV file without the full name

这里 Python 很新。我正在尝试从文件夹中读取文件,但不知道其全名。 例如 AAA_05212021.csv 是位于 C:\test\ 中的文件名 AAA 是文件名的已知部分。其余的每天都在变化。

我试过了:

import pandas as pd
data = pd.read_csv(r'C:\test\AAA*.csv')

..但它似乎不起作用。 任何帮助将非常感激。谢谢!

此代码应识别所有可能的文件:

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)

当然,如果文件夹中有多个文件遵循该结构,您仍然需要以某种方式选择一个,但如果您不挑剔的话,这可以像 files[0] 一样简单。

您可以为此使用 glob。 Glob 将 return 匹配模式的文件列表。由于目录中只有一个文件与模式匹配,您可以使用索引 0:

获取它
from glob import glob
import pandas as pd

file = glob('C:\test\AAA*.csv')[0]
data = pd.read_csv(file)