python - Python查找最近的文件很慢
问题描述
我是在做错什么,还是在应该相当慢的文件路径位置找到最新的文件?
下面的代码需要 3 分钟以上。这是否可以通过约 850 个文件的列表进行解析?
我正在使用正则表达式模式仅查找 .txt 文件,因此在通过我的文件共享位置进行搜索后,它会返回约 850 个文件的列表。这是它解析通过 key=os.path.getctime 获取 max(File) 的列表,我尝试使用 sort 而不是 max 并仅获取顶部文件,但这并没有更快。
import os
import glob
path='C:\Desktop\Test'
fileRegex='*.*txt'
latestFile = get_latest_file(filePath, fileRegex)
def get_latest_file(path,fileRegex):
fullpath = os.path.join(path, fileRegex)
list_of_files = glob.iglob(fullpath, recursive=True)
if not list_of_files:
latestFile=''
latestFile = max(list_of_files, key=os.path.getctime)
return latestFile
解决方案
尝试使用os.scandir()
,这大大加快了我的文件搜索速度。
推荐阅读
- python - 使用python,如何将新项目写入CSV文件的新行
- r - 银行客户流失的卡方检验
- python - 执行 pyinstaller 生成的可执行文件时出错
- c# - 使用 FluentFTP 从 FTP 并发下载多个文件,最大值
- android - AWS Device Farm - java.lang.ClassNotFoundException:找不到类“androidx.test.runner.AndroidJUnitRunner”
- javascript - 设置保持正确数字输入的条件
- javascript - 如何在这个 React 组件中去抖动搜索功能?
- python - 如何在 Django Rest Framework 中的外键字段上使用过滤器
- javascript - 将数据挂载到 React 状态返回错误
- sql - 具有日期和类别维度的 SQL 表