python - 慢速文件拖网渔船——python
问题描述
我编写了一个简短的脚本,在目录树中搜索匹配的最新文件,"Data*.txt"
但速度非常慢。这是因为我不得不嵌套 for 循环(我怀疑)。
示例目录树:
ROOT
|-- <directoryNameFoo1>
| |-- from # This stays the same in each subdir...
| |-- <directoryNameBar1>
| |-- Data*.txt
|
|-- <directoryNameFoo2>
| |-- from # This stays the same in each subdir...
| |-- <directoryNameBar2>
| |-- Data*.txt
|
|-- <directoryNameFoo3>
| |-- from # This stays the same in each subdir...
| |-- <directoryNameBar3>
| |-- Data*.txt
我的问题是:是否有更好/更快的方法来搜索目录结构以查找每个子目录中匹配的最新文件"Data*.txt"
?
代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import fnmatch
__basedir = os.path.abspath(os.path.dirname(__file__))
last_ctime = None
vehicle_root = None
file_list = []
for root, dirnames, filenames in os.walk(__basedir):
vehdata = []
for filename in fnmatch.filter(filenames, 'Data*.txt'):
_file = os.path.join(root, filename)
if vehicle_root == root:
if os.path.getctime > last_ctime[1]:
last_ctime = [_file, os.path.getctime(_file)]
else:
continue
else:
file_list.append(last_ctime)
vehicle_root = root
last_ctime = [_file, os.path.getctime(_file)]
print(file_list)
解决方案
您可以使用glob搜索特定模式数据而无需任何循环。像,
import glob
glob.glob('yourdir/Data*.txt')
并glob.glob('yourdir/Data*.txt,recursive=True)
在您想在定义目录中的所有子目录中搜索时使用。
推荐阅读
- c# - 如何快速重置 XML 文件和保存的类以创建新游戏 - 在 UNITY 中
- amazon-web-services - 使用 AWS Config 更改 iam 策略时的通知
- python - 我收到以下错误消息: ValueError: cannot reindex from a duplicate axis
- c# - 如何仅在我的 c# 应用程序中读取 RFID 阅读器输出
- ios - 在tableview单元格内创建动态collectionView
- java - Java:应用程序启动方法中的异常 java.lang.reflect.InvocationTargetException
- python - Python从列表中删除每三个元素
- c# - 如何访问图片 Xamarin.Forms、SQLite、C#
- python - 如何在 Python 中从 .xlsx 读取时间?
- angular - 无法将不透明度应用于:主机颜色变量