写入 CSV 文件时 NoneType 对象不可迭代

NoneType object is not Iterable when write into CSV file

在我的第一个 Python 程序中,我尝试在从 CSV 文件加载的列表中查找重复值(CSV 文件中超过 98+ k(98 000 行)行,每行有 5 列)和像对象一样保存到列表中(我只使用 2 列,在 CNT 列中我保存了重复值的数量):

class Duplication:
  def __init__(self, pn, comp, cnt):
    self.pn = pn
    self.comp = comp
    self.cnt = cnt

  def __str__(self):
    return f'{self.pn};{self.comp};{self.cnt}\n'

  def __repr__(self):
    return str(self)

  def __hash__(self):
    return hash(('pn', self.pn,
             'competitor', self.comp))
  def __eq__(self, other):
    return self.pn == other.pn and self.comp == other.comp

之后,我 select 只列出我在列表中出现次数较多的文件,并尝试将重复的对象保存到新的 CSV 文件中:

  results = [d for d in duplicates if d.cnt > 1]
  results = set(results) 

  with open(f'fileName.csv', 'a') as f:
        f.writelines('=== Info Duplications to Delete ===\n')
        for line in results:
            f.writelines(print(line))
        f.close()    
    print(results)

我收到此错误,但结果超过 7+ k 个值,当我有一个小于 100 个值的较小列表时,我想将其保存到 CSV 文件中,数据将被保存,但此文件包含大量数据排。

我遇到了这个问题,我检查了文件和调试器中的数据,没有 None 值或看起来像问题或无效数据的东西


更新

更改后:

  with open(f'file.csv', 'a') as f:
        f.writelines('===Info ===\n')
        f.writelines(results)
        #for line in results:
        #    f.writelines(print(line))
        f.close()    
    print(results)

我收到这个错误:

运行 这个脚本需要 20 多分钟

这里:

for line in results:
    f.writelines(print(line))

print returns None,因此您将 None 传递给 writelines。但是 writelines 不想要 None。它需要一个字符串序列。

如果您有一系列字符串要写入您的文件,您可以只使用

f.writelines(results)

如果您的 results 不是字符串,但您希望将它们转换为字符串,您可以使用如下内容:

f.writelines(map(str, results))

但是如果您尝试编写 csv 文件,您可能会发现使用 the csv module 更容易。

好的,解决方法很简单,我只改变:

f.writelines(print(line))

至:

f.writelines(str(line)) 

现在一切正常