【问题标题】:"_csv.Error: line contains NULL byte" in CSV reader from STDIN来自 STDIN 的 CSV 阅读器中的“_csv.Error:行包含 NULL 字节”
【发布时间】:2014-11-24 09:52:41
【问题描述】:

CSV 文件读取时,有很多关于此错误的 StackOverflow 问题。从 STDIN 读取时出现了我的问题。

[Most SO solutions talk about tweaking the open() command which works for opening CSV files - not for reading them through STDIN]. My problem is with reading through STDIN. So please don't mark this as a duplicate.

我的python代码是:

import sys , csv
def main(argv): 
    reader = csv.reader(sys.stdin, delimiter=',')
    for line in reader:
        print line

返回的错误是:

Traceback (most recent call last):
File "mapper.py", line 19, in <module>
    main(sys.argv) 
File "mapper.py", line 4, in main
    for line in reader:
_csv.Error: line contains NULL byte

我只需忽略 for 循环中出现 NULL 字节的那一行(如果可能的话)就足够了。

【问题讨论】:

  • 那你用什么管道输入的?例如,Python CSV 阅读器不支持 UTF-16 或 UTF-32 数据。
  • 我通过管道输入了一个 CSV 文件,例如 cat log.csv | python mapper.py。我在 sublime 中打开了 CSV 文件,并查看了出现问题的行号。该行包含以下内容:2013-12-18,2013-12-18 08:19:15.0,2778,1003,1328,6112,116.68.205.197,http://jobs.example.com/jobapply_confirm.asp?mclcIbl[f^S_d[=am]np_&amp;%604^35db__j^8NUL]21ad]_bacs_%20%60uaic.^M]e%60a]p%60a^1[5a1=^iapa&amp;a1b3%602a=ci_ua8,;Firefox;25.0;Windows XP;;;,1024x768,view,438,2q8cfvt4,Undefined,BD,2q92rpej,returning,1382929479,1387351637,0,0,0 注意其中的子字符串 NUL

标签: python csv stdin


【解决方案1】:

我通过处理 CSV 异常解决了它

import sys , csv    
def main(argv): 
    reader      = csv.reader(sys.stdin, delimiter=',')
    lineCount   = 0
    errorCount  = 0
    while True:
        # keep iterating indefinitely until exception is raised for end of the reader (an iterator)
        try:
            lineCount += 1
            line = next(reader)
            print "%d - %s" % (lineCount , line)
        except csv.Error: 
            # this exception is raised when a malformed CSV is encountered... ignore it and continue
            errorCount += 1
            continue
        except StopIteration: 
            # this exception is raised when next() reaches the end of the iterator
            lineCount -= 1
            break
    print "total line: %d" % lineCount
    print "total error: %d" % errorCount

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 2014-11-20
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多