Python 获取目录中的最新文件需要很长时间才能运行

Python 获取目录中的最新文件需要很长时间才能运行,python,python-2.7,file,io,Python,Python 2.7,File,Io,我有这个代码,可以在目录中找到最新的zip文件。这个程序运行速度很快,只有很少的文件夹,但是有很多文件夹,比如789个我需要查看的文件夹,里面有zip文件,代码需要30多分钟才能生成输出。关于如何让代码运行得更快,有什么建议吗 import os, glob cwd = os.getcwd() list_of_latest = [] for (dirname, dirs, files) in os.walk(cwd): for filename in files: i

我有这个代码,可以在目录中找到最新的zip文件。这个程序运行速度很快,只有很少的文件夹,但是有很多文件夹,比如789个我需要查看的文件夹,里面有zip文件,代码需要30多分钟才能生成输出。关于如何让代码运行得更快,有什么建议吗

import os, glob

cwd = os.getcwd()

list_of_latest = []
for (dirname, dirs, files) in os.walk(cwd):
    for filename in files:
        if filename.endswith('.zip'):
            list_of_files = glob.glob(dirname + '\*.zip')
            latest_file = max(list_of_files, key=os.path.getctime) 
            if latest_file not in list_of_latest:
                list_of_latest.append(latest_file)

for i in list_of_latest:
    print i

提前谢谢

您可能没有意识到这一点,但代码中有一个冗余循环。下面是一段代码:

for filename in files:
    if filename.endswith('.zip'):
        list_of_files = glob.glob(dirname + '\*.zip')
glob.glob
将检索当前目录(由根路径
dirname
指定)中的所有zip文件。现在,如果该目录中有10个
zip
文件,您将运行
glob.glob
10次!每次都会找到相同的文件。但它仅附加到列表中的第一个

整个内部循环可以简化为以下内容:

for (dirname, dirs, files) in os.walk(cwd):
    list_of_files = glob.glob(dirname + '\*.zip')
    if len(list_of_files) == 0: 
        continue
    latest_file = max(list_of_files, key=os.path.getctime) 

    if latest_file not in list_of_latest:
        list_of_latest.append(latest_file)

该内部循环是不必要的。

您正在对目录中的所有文件进行两次迭代,一次是使用:

for filename in files:
然后:

latest_file = max(list_of_files, key=os.path.getctime) 
您可能想要的是:

for (dirname, dirs, files) in os.walk(cwd):
    list_of_files = glob.glob(dirname + '\*.zip')
    latest_file = max(list_of_files, key=os.path.getctime) 
    if latest_file not in list_of_latest:
        list_of_latest.append(latest_file)
哦,如果您使用集合而不是列表来表示最新的列表,它将允许进一步简化:

list_of_latest = set()
for (dirname, dirs, files) in os.walk(cwd):
    list_of_files = glob.glob(dirname + '\*.zip')
    latest_file = max(list_of_files, key=os.path.getctime) 
    list_of_latest.add(latest_file)

也许您可以生成并行的进程,我不知道是什么让它从30分钟变为几秒钟。我尝试了这个,但它抛出了一个ValueError,它说:max()arg是一个空序列@BlotosmetekI尝试了这个。它给了我一个ValueError,它说:max()arg是一个空序列@Coldspeed@JeanPaulMugisha现在试试吧?我加了一个IF支票。“JeaPauluMuigia没有问题。如果这个答案对你有帮助,一定要考虑接受它。干杯。”