慢速文件拖网渔船-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')

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...