我寫了一個(gè)簡短的腳本,在目錄樹中搜索匹配的最新文件"Data*.txt",但速度非常慢。這是因?yàn)槲也坏貌磺短?for 循環(huán)(我懷疑)。示例目錄樹: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我的問題是:是否有更好/更快的方法來搜索目錄結(jié)構(gòu)以找到"Data*.txt"每個(gè)子目錄中匹配的最新文件?代碼:#!/usr/bin/env python# -*- coding: utf-8 -*-import osimport fnmatch__basedir = os.path.abspath(os.path.dirname(__file__))last_ctime = Nonevehicle_root = Nonefile_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)
1 回答

鴻蒙傳說
TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以使用glob來搜索特定模式數(shù)據(jù)而無需任何循環(huán)。喜歡,
import?glob glob.glob('yourdir/Data*.txt')
glob.glob('yourdir/Data*.txt,recursive=True)
當(dāng)你想在你定義的目錄中的所有子目錄中搜索時(shí)使用。
添加回答
舉報(bào)
0/150
提交
取消