首页 > 解决方案 > 通过 glob 打开一定数量的文件

问题描述

我正在尝试使用glob在一个文件夹中打开 excel 文件,然后将concat它们放入 1 个文件,但是打开所有文件然后像这样连接(每个文件内容大约 20000 行)需要很长时间。

所以我想问一下是否有使用glob打开一定数量的文件?例如:所有文件中的最近 30 个文件。或者有没有其他方法可以做到

谢谢和最好的问候

标签: pythonpandas

解决方案


或者有没有其他方法可以做到

listdir我通常通过使用 os 方法列出给定目录(例如 )中的所有可用文件来处理这个问题path_to_files,然后使用 pandasread_csvread_excel方法打开它们并将它们附加到 alist_of_dataframes以连接:

import os 
import pandas as pd
from pathlib import Path

path_to_files = Path('...') #The path to the folder containing your excel files

list_of_dataframes = []
for myfile in os.listdir(path_to_files):
     pathtomyfile = path_to_files / myfile
     list_of_dataframes.append(pd.read_csv(pathtomyfile)) 

df=pd.concat(list_of_dataframes)

要加载的文件数可以通过索引指定,例如最后 30 个文件:

for myfile in os.listdir(path_to_files)[-30:]


推荐阅读