Python csv 字段上的拆分字符串 (',') 问题

Python split string(',') issue on a csv field

我遇到一个问题,我正在将 csv 文件读取为从应用程序导出的文件(对我来说更容易获得读取为 csv 的结果)。我的代码正在读取该文件并将其导入列表。然后我遍历列表并保存到适当的字段。我正在使用内置方法 .split(',') 并且它在某种程度上非常有效。我能够按照我想要的方式获得我的颜色,但一直到第 70 行都是我的错误发生。我发现由于某个字段有多行导致程序将每一行导入列表并为每一行创建一列。尝试拆分时如何忽略多行的文件?

您可以通过对其执行字符串 .replace('\n', ' ') 来去除字段中的换行符。

I am found that due to a certain field has multiple lines is causing the program to import each line into the list and creating a column for each line. How can I ignore a filed that has multiple lines when trying to do a split?

与其尝试自己解析文件并处理边缘情况,不如使用核心 csv 模块。

假设您有这样的数据:

 +----------+-----------+----------+
 | Aaa      | Bbb       | Ccc      |
 +---------------------------------+
 | 1        | 2         | 3        |
 +---------------------------------+
 | Foo      | Bar       | Goo      |
 |          | Baz       |          |
 |          | Bag       |          |
 +---------------------------------+
 | 5        | 6         | 7        |
 +----------+-----------+----------+

导出为这样的 CSV 文件:

$cat test_file.csv
Aaa,Bbb,CCC
1,2,3
Foo ,"Bar
Baz
Bag",Goo
5,6,7

您可以通过以下方式轻松阅读:

import csv

with open('test_file.csv', 'rb') as csvfile:
    csv_reader = csv.reader(csvfile)
    for row in csv_reader:
        print row

给出:

$python test_reader.py

['Aaa', 'Bbb', 'CCC']
['1', '2', '3']
['Foo ', 'Bar\nBaz\nBag', 'Goo']
['5', '6', '7']