使用fileinput python模块从文件中读取行时出现“'NoneType'对象不可迭代”错误

我正在使用文件输入库的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.

P.S。 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_13_2019.txt',),'_isstdin':False,'_filelineno':0,'无','_ backupfile' ``

zhenzhengdeyu 回答:使用fileinput python模块从文件中读取行时出现“'NoneType'对象不可迭代”错误

这里有两个地方要遍历集合。

for file in filelist:
for xline in f:

该错误表示filelistf返回None而不是任何元素。换句话说,没有什么可迭代的,它甚至不是一个空集合-它没有值。

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

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

您遇到错误

  

'NoneType'对象不可迭代

当您尝试遍历None或空值时

例如

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

在上述情况下,当您尝试遍历None值时,您会收到错误消息。

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

for file in filelistfor xline in f

所以filelist为None或f为None

本文链接:https://www.f2er.com/3111617.html

大家都在问