python - 通过 glob 打开一定数量的文件
问题描述
我正在尝试使用glob
在一个文件夹中打开 excel 文件,然后将concat
它们放入 1 个文件,但是打开所有文件然后像这样连接(每个文件内容大约 20000 行)需要很长时间。
所以我想问一下是否有使用glob打开一定数量的文件?例如:所有文件中的最近 30 个文件。或者有没有其他方法可以做到
谢谢和最好的问候
解决方案
或者有没有其他方法可以做到
listdir
我通常通过使用 os 方法列出给定目录(例如 )中的所有可用文件来处理这个问题path_to_files
,然后使用 pandasread_csv
或read_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:]
推荐阅读
- cmake - 在安装时为 cmake 项目设置适当的 rpath
- r - 为什么 chron 包从 2030 年开始奇怪地处理 2 位数年份?
- javascript - 防止 slick.js 打开链接 onclick next
- wordpress - 编辑重定向的 Wordpress 站点
- android - 在 textView 上显示图像位置
- javascript - 在 vscode 语言服务器中预打开文件
- python - CSV 中的 Snowflake COPY INTO 列
- ssas - 使用 DAX 实施 SSAS RLS
- scala - Scala元组添加保持序列相同的顺序
- javascript - 通过 jQuery(或类似方法)使用 timeAgo 来显示用户(客户端)进入或刷新页面的时间