2017-06-21 161 views
0

我正在编写脚本来检查文件并打印出zip文件及其创建日期。我的程序对少于5MB的数据有效,但如果我在超过15MB的数据上运行它,生成输出需要几个小时。以下是我的代码示例。我怎样才能优化我的代码,使其运行速度更快?需要很长时间才能运行的python脚本

import os, argparse 
from datetime import datetime 


#Returns a list of directories of all zip files. 
def findZip_Dir_list(cwd): 
    userList = [] 
    for (dirname, dirs, files) in os.walk(cwd): 
     for filename in files: 
      if filename.endswith('.zip'): 
       fileDir = os.path.join(dirname, filename) 
       t = os.path.getmtime(fileDir) 
       userList.append(os.path.join(fileDir, str(t))) 
    return userList 

cwd = os.getcwd() 
testList = findZip_Dir_list(cwd) 

print(tesList) 
+0

也许https://pypi.python.org/pypi/glob2? – Kevin

回答

0

使用glob2

import os, glob2 

# Returns a list of directories of all zip files. 
def findZip_Dir_list(cwd): 
    userList = [] 
    all_zip_files = glob2.glob(os.path.join(cwd, '**/*.zip')) 
    for file in all_zip_files: 
     t = os.path.getmtime(file) 
     userList.append(os.path.join(file, str(t))) 
    return userList 


cwd = os.getcwd() 
testList = findZip_Dir_list(cwd) 

print(testList) 
+0

是python 2.7中的glob2吗?我试图导入它,但它说有一个名为glob2的模块。此外,这是否减少了它运行所花费的时间? – LearningEveryday

+0

你必须安装它,但是这是2.7。对我来说似乎很好,但我没有检查你的方法 – Kevin

相关问题