2011-10-23 128 views
1

只写了我的第一个python程序!我将zip文件作为邮件附件保存在本地文件夹中。该程序检查是否有新文件,如果有一个文件解压缩zip文件,并根据文件名提取到不同的文件夹。当我运行我的代码时,出现以下错误:“'NoneType'对象不可迭代”错误

Traceback(最近调用最后一次):文件“C:/Zip/zipauto.py”,第28行,用于new_files中的文件:TypeError:'NoneType'object是不可迭代的

任何人都可以请告诉我我哪里错了。

非常感谢您的时间,

纳文 这里是我的代码:

import zipfile 
import os 

ROOT_DIR = 'C://Zip//Zipped//' 
destinationPath1 = "C://Zip//Extracted1//" 
destinationPath2 = "C://Zip//Extracted2//" 

def check_for_new_files(path=ROOT_DIR): 

    new_files=[] 
    for file in os.listdir(path): 
     print "New file found ... ", file 

def process_file(file): 

    sourceZip = zipfile.ZipFile(file, 'r') 
    for filename in sourceZip.namelist(): 
      if filename.startswith("xx") and filename.endswith(".csv"): 
        sourceZip.extract(filename, destinationPath1) 
      elif filename.startswith("yy") and filename.endswith(".csv"): 
        sourceZip.extract(filename, destinationPath2) 
        sourceZip.close() 

if __name__=="__main__": 
    while True: 
      new_files=check_for_new_files(ROOT_DIR) 
      for file in new_files: # fails here 
        print "Unzipping files ... ", file 
        process_file(ROOT_DIR+"/"+file) 

回答

6

check_for_new_files没有return statement,因此隐含返回无。因此,

new_files=check_for_new_files(ROOT_DIR) 

套new_files到None,你不能在None迭代。

返回check_for_new_files读文件:

def check_for_new_files(path=ROOT_DIR): 
    new_files = os.listdir(path) 
    for file in new_files: 
     print "New file found ... ", file 
    return new_files 
+0

aha..that解决它..非常感谢你 – Navin

1

这里的答案是你的下2个问题:

(1)while True::你的代码将永远循环。 (2)您的功能check_for_new_files不检查新文件,它检查任何文件。您需要将每个传入文件在处理完成后移动到存档目录,或者使用某种时间戳机制。

+0

yes..i使用shutil模块将传入文件移动到另一个目录后处理 – Navin

相关问题