Skip to main content
 首页 » 编程设计

Python CSV 阅读器,CSV 格式化

2025年05月04日11shangdawei

我有一个 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' 但没有成功。 有什么想法吗?

请您参考如下方法:

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