亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

慢文件拖網漁船——python

慢文件拖網漁船——python

倚天杖 2023-06-20 16:21:14
我寫了一個簡短的腳本,在目錄樹中搜索匹配的最新文件"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 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貢獻1865條經驗 獲得超7個贊

您可以使用glob來搜索特定模式數據而無需任何循環。喜歡,

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

glob.glob('yourdir/Data*.txt,recursive=True)當你想在你定義的目錄中的所有子目錄中搜索時使用。


查看完整回答
反對 回復 2023-06-20
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號