【问题标题】:Python 3 - '_csv.Error: line contains NULL' error byte when reading csv filePython 3 - '_csv.Error: line contains NULL' 读取 csv 文件时的错误字节
【发布时间】:2018-04-12 10:33:00
【问题描述】:

我正在尝试读取包含 NUL 的 csv 文件 带 csv 阅读器 我搜索了很多方法来读取文件而没有错误,但找不到。

编辑: 添加文件的相关部分: https://drive.google.com/open?id=1rtF3ck6QymtH4_n4iUjavPnxZiryq_Q4

我的代码:

   with codecs.open(log_path, 'r') as csv_file:
        log_reader = csv.DictReader(csv_file)
        for line in log_reader:
            if line['Addition Information'] == str 
               # do something 

将不胜感激任何帮助 谢谢, Avishay

【问题讨论】:

  • 您可以发布您的 CSV 文件吗?
  • 我添加了相关部分的链接

标签: python python-3.x csv


【解决方案1】:

csv.reader()(因此还有csv.DictReader())根本无法处理包含空字节的文件。

一个可能的解决方案是在读取输入文件时替换空字节,例如通过使用生成器表达式,因为reader() 将任何支持迭代器协议的对象作为参数:

with codecs.open(log_path, 'r') as csv_file:
    log_reader = csv.DictReader((l.replace('\0', '') for l in csv_file))
    for line in log_reader:
        if line['Addition Information'] == str 
           # do something 

【讨论】:

  • 工作得很好!现在速度有点慢,但已经成功了,非常感谢!
  • 这对我也有用。谢谢,是的,看起来有点慢。但很好。
【解决方案2】:

尝试像这样修改你的代码:

with codecs.open(log_path, 'r', encoding='utf-8', errors='backslashreplace') as csv_file:
        log_reader = csv.DictReader(csv_file)
        for line in log_reader:
            if line['Addition Information'] == str 
               # do something 

【讨论】:

    猜你喜欢
    • 2015-11-17
    • 2021-12-04
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2020-09-21
    • 2019-04-29
    • 2021-12-17
    相关资源
    最近更新 更多