【问题标题】:" 'NoneType' object is not iterable" error when using fileinput python module to read lines from file使用 fileinput python 模块从文件中读取行时出现“'NoneType'对象不可迭代”错误
【发布时间】:2020-03-09 00:48:26
【问题描述】:

我正在使用 fileinput 库的 Linux 环境中运行以下 python 代码。

    filelist = glob.glob(os.path.join(LOCAL_DESTINATION, "*.*"))
    for file in filelist:
        if comment_type.lower() == 'header':
            f = fileinput.input(file, inplace=1)
            print(f)
            print(f.__dict__)
            for xline in f:
                print(4567)
                if f.isfirstline():
                    sys.stdout.write(comments + '\n' + xline)
                else:
                    sys.stdout.write(xline)

The stderr I see even though the file is present in the LOCAL_DESTINATION folder:
'NoneType' object is not iterable
Exception ignored in: <bound method FileInput.__del__ of <fileinput.FileInput object at 0x7fb6164ed240>>
Traceback (most recent call last):
  File "/usr/lib/python3.5/fileinput.py", line 229, in __del__
  File "/usr/lib/python3.5/fileinput.py", line 233, in close
  File "/usr/lib/python3.5/fileinput.py", line 290, in nextfile
TypeError: 'NoneType' object is not callable``


Can someone tell what could be the problem.

附: f.dict 打印出以下内容: {'_file':无,'_backup':'','_openhook':无,'_filename':无,'_savestdout':无,'_mo​​de':'r','_inplace':1,'_startlineno': 0,'_files':('4f5b11ef-601f-4607-a4d0-45173d2bbc53 / q3_2019_placementguid_555168561629745350_f99a8d275e4_11_f99a8d275e4_11_13_2019.txt',),'_isstdin':false,'_filelineno':0,'_backupfilename':none,'_output':none}` ``

【问题讨论】:

  • 提供完整的错误信息
  • @AkshayNevrekar 会回复你

标签: python python-3.5


【解决方案1】:

这里有两个地方你正在迭代集合。

for file in filelist:
for xline in f:

错误意味着filelistf 返回None 而不是任何元素。换句话说,没有什么可以迭代的,它甚至不是一个空集合——它没有价值。

您可以使用下面的列表来避免错误。但是,您必须检查并处理空集合。

for file in filelist or []:
for xline in f or []:

【讨论】:

  • 我修复了“空集合”部分,也许我越界了,你告诉我这样行不行。
  • 当我打印 f 时,我得到
  • @Kuldeep,打印出来的意思是,你正在打印内存地址。你可以在这里阅读更多内容docs.python.org/2/library/fileinput.html
  • @CorentinPane,没关系。
【解决方案2】:

你得到错误

'NoneType' 对象不可迭代

当您尝试循环遍历 None 或空值时

例如。

k = None
for i in k:
    print(k)

在上述情况下,当您尝试迭代 None 值时会出现错误。

在您的情况下,您有 2 个 for 循环

for file in filelistfor xline in f

所以filelist 是无或f 是无

【讨论】:

  • 当我打印 f 时,我得到
  • 对于其中一次迭代,您必须获得None
  • 好的,我会检查并告诉你谢谢你的回答:)
猜你喜欢
  • 2021-01-23
  • 2021-11-26
  • 1970-01-01
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 2016-09-11
  • 2013-06-03
相关资源
最近更新 更多