Python Unicode CSV,引号之间有换行符

时间:2014-01-23 09:58:39

标签: python csv unicode newline

我正在使用unicodecsv在Python中循环遍历csv文件的行。 我的CSV文件中的字符串在引号之间,但csv阅读器仍将新行视为行分隔符。

这是我的代码:

with open(path, mode='rU') as f:
    reader = unicodecsv.reader(f, delimiter=b',', quoting=csv.QUOTE_MINIMAL, quotechar=b'"', lineterminator="\n")

    for count, row in enumerate(reader):
        if count < row_offset:
            continue
        record = {}
        for col, mapper in enumerate(mappers):
            ...
            ...                                               

以下是csv行的示例:

"test","this line will
continue on the next line","another column",

出于某种原因,读者会将其读作2行而不是1行。

修改

新示例CSV行:

628,2012-07-27 01:59:32,000445,MARC,525,"HE547                           ","1",2012-07-27,,,,,,,,"This is an example, this is a test line.
new line but it is in the same csv line, followed by some enters!


",

1 个答案:

答案 0 :(得分:2)

逗号后面有空格;在阅读器上设置skipinitialspace=True以忽略这一点:

reader = unicodecsv.reader(f, delimiter=b',', skipinitialspace=True, quoting=csv.QUOTE_MINIMAL, quotechar=b'"', lineterminator="\n")

使用常规reader.csv()对象进行演示:

>>> reader = csv.reader(f, delimiter=b',', quoting=csv.QUOTE_MINIMAL, quotechar=b'"')
>>> next(reader)
['test', ' "this line will']
>>> f.seek(0)
>>> reader = csv.reader(f, skipinitialspace=True, delimiter=b',', quoting=csv.QUOTE_MINIMAL, quotechar=b'"')
>>> next(reader)
['test', 'this line will\ncontinue on the next line', 'another column', '']

注意如果没有设置skipinitialspace标志,第二列以' "...开头,所以空格和引号。并不是因为空格而无法识别换行符,而是 quote

另一种可能性是您的输入数据使用不同的引用字符。无论哪种方式,csv.reader()都无法识别您的列被引用。您需要查看不完整列的repr(),以查看从阅读器返回时包含的字符,以及该值中仍存在哪个引号字符(如果有)。

但是,如果没有准确的样本CSV数据,很难说你实际遇到了什么问题。