如何解决慢速文件拖网渔船-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来搜索特定的图案数据而不会循环。 喜欢,
s = df2.set_index('occupation_2')['average_salary']
df1['salary'] = df1['salary'].fillna(df1['occupation_1'].map(s))
并在您要在定义的目录中的所有子目录中搜索时使用import glob
glob.glob('yourdir/Data*.txt')
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。