Skip to main content
 首页 » 编程设计

python之"' 无类型 ' object is not iterable"错误

2025年05月04日11kenshinobiy

刚刚写了我的第一个 python 程序!我在邮件中将 zip 文件作为附件保存在本地文件夹中。该程序检查是否有任何新文件,如果有,它会提取 zip 文件,并根据文件名将其提取到不同的文件夹。当我运行我的代码时,出现以下错误:

回溯(最近调用最后):文件“C:/Zip/zipauto.py”,第 28 行,在 new_files 中的文件:TypeError:'NoneType' 对象不可迭代

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

非常感谢您的宝贵时间,

纳文 这是我的代码:

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) 

请您参考如下方法:

check_for_new_files 没有 return statement ,因此隐式返回 None。因此,

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