首页 > 解决方案 > 慢速文件拖网渔船——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)

标签: pythonos.pathfnmatchnested-for-loop

解决方案


您可以使用glob搜索特定模式数据而无需任何循环。像,

import glob
glob.glob('yourdir/Data*.txt')

glob.glob('yourdir/Data*.txt,recursive=True)在您想在定义目录中的所有子目录中搜索时使用。


推荐阅读