读取目录中的所有excel文件到dataframe中,并使用文件名添加一列



我有一个文件夹,其中包含一些excel文件。我想把它们都读到一个数据框,但同时添加一个日期列。日期包含在每个文件名中。我有代码来读取文件内容,但不确定如何从文件名读取日期。

这是我读取文件的代码。

import pandas as pd
import glob
all_data = pd.DataFrame()
for f in glob.glob('my directory/*.xlsx'):
df = pd.read_excel(f)
all_data = all_data.append(df,ignore_index=True)

我假设我需要添加df['date']=但不确定如何从文件名中获取日期。所有的文件名都有相同的格式,在文件名的末尾加上日期。例如,'Data report 06.08.21'。

非常感谢你的帮助。

import pandas as pd
import glob, os, re
all_data = pd.DataFrame()
for f in glob.glob('my directory/*.xlsx'):
_, f_file= os.path.split(f)
file_date=re.findall(r'd{2}.d{2}.d{2}', f_file)
df = pd.read_excel(f)
df['date'] =str(file_date)
all_data = all_data.append(df,ignore_index=True)

最新更新