Python CSV阅读器,CSV格式

时间:2014-01-14 00:04:26

标签: python excel csv

我有一个看起来不会破碎的CSV。其中一列包含完整的电子邮件和随后的其他逗号。格式如下:

ID   | Info   |  Email           | Notes
--------------------------------------------------
1234 | Sample |  Full email here,| More notes here
              |  and email wraps.|
--------------------------------------------------
5678 | Sample2|  Another email,  |  More notes
--------------------------------------------------
9011 | Sample3|  More emails     |  Etc.
--------------------------------------------------

我正在使用CSV读取器,它将每个新行输出为新行,但它不正确。 例如,我得到了:

Line 1: 1234 | Sample |  Full email here,| More notes here
Line 2:               |  and email wraps.|
Line 3: 5678 | Sample2|  Another email,  |  More notes
Line 4: 9011 | Sample3|  More emails     |  Etc.

我需要它能像Excel或Libre Office那样识别单元格分隔符,并得到这个:

Line 1: 1234 | Sample |  Full email here, and email wraps.| More notes here
Line 2: 5678 | Sample2|  Another email,  |  More notes
Line 3: 9011 | Sample3|  More emails     |  Etc.

我有这段代码:

 import csv
 import sys
 csv.field_size_limit(sys.maxsize)
 file = "myfile.csv"
 with open(file, 'rU') as f:
     freader = csv.reader(f, delimiter = '|', quoting=csv.QUOTE_NONE)
     for row in freader:
         print(','.join(row))

我尝试了delimiter =','或delimiter ='\ n'但没有运气。 有什么想法吗?

1 个答案:

答案 0 :(得分:8)

CSV stands for comma separated values. 虽然可以将分隔符更改为制表符,管道或任何您想要的内容,但问题是CSV是非常原始的,基于行的格式。

问题在于您的第二条记录,该记录跨越已损坏的行从CSV文件的角度来看。 Python CSV库不是为了容纳这样的东西而设计的,因为它不是CSV文件的样式。

要做你要问的事情,最好编写自己的解析器来破坏分隔符上的每一行并根据某些逻辑进行合并。这应该是相对简单的 iff ID列永远不会跨越两行。

至于如何实际编写代码,您需要一个如下过程:

Initialise array X
Read each line L of file F:
    If the ID field is empty then merge each entry into the previous line L-1
    Otherwise append the line L to array X