【问题标题】:"'NoneType' object is not iterable" error“'NoneType' 对象不可迭代”错误
【发布时间】:2011-12-13 16:47:29
【问题描述】:

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

Traceback(最近一次调用最后一次):文件“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)

【问题讨论】:

    标签: python


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      这是您接下来 2 个问题的答案:

      (1)while True::你的代码将永远循环。

      (2) 你的函数check_for_new_files 不检查新文件,它检查任何 文件。您需要在处理完每个传入文件后将其移动到存档目录,或者使用某种时间戳机制。

      【讨论】:

      • 是的..我使用shutil模块将传入的文件在处理后移动到另一个目录
      【解决方案3】:

      例如,student_grade = dict(zip(names, grades)) 确保名称和等级是列表,并且都至少有一个以上的项目可以迭代。这对我有帮助

      【讨论】:

        猜你喜欢
        • 2016-09-11
        • 2014-10-09
        • 2013-12-01
        • 2013-06-03
        • 2020-03-18
        • 2012-03-26
        • 2018-06-25
        • 2016-02-08
        • 2020-05-06
        相关资源
        最近更新 更多