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

2024-04-27 01:13:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件csv方法代码程序应用程序列表颜色
2条回答

您可以通过对字段执行字符串.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']

相关问题 更多 >