【问题标题】:Getting an error: Line Contains Null, Not sure the cause [duplicate]收到错误:行包含空值,不确定原因[重复]
【发布时间】:2020-05-11 17:01:35
【问题描述】:

我收到错误消息:line contains NUL。我认为这意味着我的 CSV 文件中有一个奇怪的字符。但是这个程序和导入文件在不同的机器(两台 Mac)上工作,所以我不知道原因是 Python 的不同版本还是我如何运行它。通过阅读其他条目,我认为这行也可能是原因:

reader = csv.reader(open(filePath, 'r', encoding="utf-8-sig", errors="ignore"))

感谢任何帮助/建议!

paths CWD=/Users/sternit/Downloads/Ten-code-4, CPD=/Users/sternit/Downloads/Ten-code/
Traceback (most recent call last):
  File "/Users/sternit/Downloads/Ten-code-4/Master.py", line 145, in <module>
    main()
  File "/Users/sternit/Downloads/Ten-code-4/Master.py", line 114, in main
    playerLists = loadFiles(CPD + "PlayerFiles/")
  File "/Users/sternit/Downloads/Ten-code-4/Master.py", line 50, in loadFiles
    for n, row in enumerate(reader):
_csv.Error: line contains NUL

【问题讨论】:

标签: python


【解决方案1】:

这应该可以正常工作:

data_initial = open(filePath, "rb")
data = csv.reader((line.replace('\0','') for line in data_initial), delimiter=",")

【讨论】:

    【解决方案2】:

    如果csv 模块说您的阅读文件中有一个“NULL”(愚蠢的消息,应该是“NUL”)字节,我建议您检查一下文件中的内容。

    尝试使用rb,它可能会解决问题:

    reader = csv.reader(open(filePath, 'rb', encoding="utf-8-sig", errors="ignore"))
    
    

    取决于文件的生成方式,可能包含 NULL 字节,因此您可能需要

    1. 用编辑器打开,看看是不是合理的CSV文件,如果文件太大,在CLI中使用nanohead

    2. 使用其他库,如 pandas,可能更健壮。

    3. 如果问题依旧,可以将'\x00',全部替换为空字符串:

    fi = open(filePath, 'rb')
    data = fi.read()
    fi.close()
    fo = open('mynew.csv', 'wb')
    fo.write(data.replace('\x00', ''))
    fo.close()
    

    【讨论】:

    • 谢谢,比尔。现在就试试吧!
    • 最佳实践是使用with 语句打开文件,即with open(filePath, 'rb') as fi: data = fi.read()with open('mynew.csv', 'wb') as fo: fo.write(data.replace('\x00', ''))
    • @wjandrea,你使用with是对的,但这里是打开并保存它,所以我觉得不用它就可以了。感谢您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2016-08-22
    相关资源
    最近更新 更多