如果超过指定时间

时间:2017-03-30 22:15:28

标签: python search optimization

我对python和编码一般都很陌生,我正在寻找一些优化代码的帮助。我正在尝试编写一个脚本,该脚本将在某个路径下找到所有“Temp”文件夹,找到每个文件的最新文件年龄,并且只有在找不到比1小时更新的文件时才继续删除。目前,删除机制尚未实现,但一旦找到并检查了文件,就应该很容易添加。

我当前的迭代在我的几千个文件的测试文件夹结构上运行没有问题,但是当我尝试在真实的东西(5b +文件)上运行时,它当然需要永远。几乎所有这些文件都位于“Temp”文件夹之外。有没有办法将文件搜索隔离到Temp文件夹?

以下是我目前的代码。

import os
import fnmatch
import time
import calendar


def find_newest_file(path):
    for cur_path, dirnames, filenames in os.walk(path):
        for filename in filenames:
            yield os.path.join(cur_path, filename)

matches = []
latest_file = []
for root, dirnames, filenames in os.walk("--Path To Network Share--"):
    for filename in fnmatch.filter(dirnames, '*Temp'):
            matches.append(os.path.join(root, filename))
            latest_file.append(max(find_newest_file(os.path.join(root, filename)),
                              key=os.path.getmtime))

counter = 0
newestfileage = []
for name in matches:
    newestfileage.append((calendar.timegm(time.gmtime()) - os.stat(latest_file[counter]).st_mtime) / 3600)
    counter += 1

if min(newestfileage) < 1:
    print("\nToo new of an Entry in Temp folders, stopping.\nNewest file is only", min(newestfileage)*60,"Minutes Old")
else:
    print("\nAll Temp files are older than 1 hour old, proceeding.")

如果对此有完全不同的方法,我全都听见了。

1 个答案:

答案 0 :(得分:0)

在我看来,你只需要做以下事情:

import re
import os

temp_regex = re.compile(r'.*Temp')
matches = []
latest_file = []
for root, dirnames, filenames in os.walk("--Path To Network Share--"):
    if temp_regex.match(os.path.basename(root)):
        matches.append(root)
        fullnames = (os.path.join(root, filename) for filename in filenames)
        latest_file.append(max(fullnames, key=os.path.getmtime)

免除find_newest_file函数,该函数会在匹配的目录上启动更多os.walks ,但是您访问它们的次数与它们在根目录下的次数相同find_newest_file。这让你可怕地扩展。

顺便说一句,如果您在每次迭代中递增,请不要保留counter变量,而是使用enumerate

newestfileage = []
for i, name in enumerate(matches):
    newestfileage.append((calendar.timegm(time.gmtime()) - os.stat(latest_file[i]).st_mtime) / 3600)

或者更好的是,我认为你只需要迭代for file in latest_file,因为你从不使用match而只使用i来索引latest_file。实际上,上述内容可能在os.walk传递期间完成:

temp_regex = re.compile(r'.*Temp')
matches = []
latest_file = []
newestfileage = []

for root, dirnames, filenames in os.walk("--Path To Network Share--"):
    if temp_regex.match(os.path.basename(root)):
        matches.append(root)
        fullnames = (os.path.join(root, filename) for filename in filenames)
        latest = max(fullnames, key=os.path.getmtime)
        latest_file.append(latest)
        newestfileage.append(calendar.timegm(time.gmtime()) - os.stat(latest).st_mtime) / 3600)