Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
慢速文件拖网渔船——python_Python_Os.path_Fnmatch_Nested For Loop - Fatal编程技术网

慢速文件拖网渔船——python

慢速文件拖网渔船——python,python,os.path,fnmatch,nested-for-loop,Python,Os.path,Fnmatch,Nested For Loop,我编写了一个简短的脚本,在目录树中搜索与“Data*.txt”匹配的最新文件,但速度非常慢。这是因为我必须嵌套for循环(我怀疑) 目录树示例: ROOT |-- <directoryNameFoo1> | |-- from # This stays the same in each subdir... | |-- <directoryNameBar1> | |-- Data*.tx

我编写了一个简短的脚本,在目录树中搜索与
“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
您可以使用搜索特定的图案数据,而无需任何循环。 像


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

我仍然需要在glob输出的列表上循环,这几乎需要相同的时间。
#!/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)
import glob
glob.glob('yourdir/Data*.txt')