“TypeError:'NoneType'对象不可迭代”应该是什么列表

时间:2013-12-05 21:32:54

标签: python list function

我有一些代码是基于我发现的here,但由于我的声誉很低,我无法发表评论。我还查看了与此相同错误相关的所有其他帖子,但是,由于我对编程和Python不熟悉,我还没有找到解决方案。

是的,所以我有以下代码:

import zipfile, os

def dirEntries(dir_name):
    ''' Creates a list of all files in the folder 'dir_name' which we assign when we call the function later'''

    fileList = []
    '''creates an empty list'''
    for file in os.listdir(dir_name):
        '''for all files in the directory given'''
        dirfile = os.path.join(dir_name, file)
        '''creates a full file name including path for each file in the directory'''
        if os.path.isfile(dirfile) and os.path.splitext(dirfile)[1][1:]!='lock':
            '''if the full file name above is a file and it does not end in 'lock' it will be added to the list created above'''
            fileList.append(dirfile)

def makeArchive(fileList, archive, root):
    """
    'fileList' will be a list of file names - full path each name
    'archive' will be the file name for the archive with a full path (ex. "C:\\GIS_Data\\folder.zip")
    """
    a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)

    for f in fileList:
        a.write(f, os.path.relpath(f, root))
        '''I don't completely understand this, but the 'relpath' part seemed integral to not having the entire folder structure saved in the zip file'''
    a.close()

makeArchive(dirEntries(ptdir), ptdir+"pts.zip", ptdir)
makeArchive(dirEntries(polydir), polydir+"polys.zip", polydir)

'ptdir'和'polydir'在代码的早期部分中定义。

我得到以下内容:

Traceback (most recent call last):
  File "C:\Python27\ArcGIS10.1\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
    exec codeObject in __main__.__dict__
  File "C:\GIS_Data\Working\Python\DatabaseExport\ExportScriptTEST.py", line 181, in <module>
    makeArchive(dirEntries(ptdir), ptdir+"pts.zip", ptdir)
  File "C:\GIS_Data\Working\Python\DatabaseExport\ExportScriptTEST.py", line 177, in makeArchive
    for f in fileList:
TypeError: 'NoneType' object is not iterable

我已经在交互式窗口中完成了这个过程,当我拆开这些函数并一点一点地提供它们时,填充列表没有问题,但是当我一起运行它时,我得到了错误。是由于某种原因没有填充列表的问题,还是还有其他事情发生。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:4)

您没有在此函数dirEntries(dir_name)中返回任何内容,因此默认情况下它会返回None

在最后添加一个return语句来解决这个问题:

def dirEntries(dir_name):
    ''' Creates a list of all files in the folder 'dir_name' which we assign when we call the function later'''

    fileList = []
    '''creates an empty list'''
    for file in os.listdir(dir_name):
        '''for all files in the directory given'''
        dirfile = os.path.join(dir_name, file)
        '''creates a full file name including path for each file in the directory'''
        if os.path.isfile(dirfile) and os.path.splitext(dirfile)[1][1:]!='lock':
            '''if the full file name above is a file and it does not end in 'lock' it will be added to the list created above'''
            fileList.append(dirfile)
    return fileList