使用pathlib和defaultdict
设置目标路径以便写入文件。from pathlib import Path
from collections import defaultdict
from datetime import datetime
my_path = 'your_dir'
files = [f for f in Path(my_path).glob('*.csv')]
# create a dictionary with file as key and time as value.
file_dict = dict(
zip(
files,
[datetime.fromtimestamp(f.stat().st_mtime).strftime("%m_%d_%y") for f in files],
)
)
#reverse engineer the list so it has a list appended by the date.
file_merger_list = defaultdict(list)
for k,v in file_dict.items():
file_merger_list[v].append(k)
# make folder to write to.
target_path = Path(your_path).joinpath('mergedfiles').mkdir(parents=True,exists_ok=False)
for date,file in file_merger_list.items():
df = pd.concat([pd.read_csv(f) for f in file])
df.to_csv(target_path.joinpath(f"combined_{date}.csv"))
输出['combined_01_02_20.csv',
'combined_01_28_20.csv',
'combined_12_02_19.csv',
'combined_12_09_19.csv']