Separate data with a comma CSV Python

偶尔善良 提交于 2019-12-13 06:52:33

问题


I have some data that needs to be written to a CSV file. The data is as follows

A        ,B    ,C
a1,a2    ,b1   ,c1
a2,a4    ,b3   ,ct

The first column has comma inside it. The entire data is in a list that I'd like to write to a CSV file, delimited by commas and without disturbing the data in column A. How can I do that? Mentioning delimiter = ',' splits it into four columns on the whole.


回答1:


Just use the csv.writer from the csv module.

import csv

data =  [['A','B','C']
         ['a1,a2','b1','c1']
         ['a2,a4','b3','ct']]

fname = "myfile.csv"    
with open(fname,'wb') as f:
    writer = csv.writer(f)
    for row in data:
        writer.writerow(row)

https://docs.python.org/2/library/csv.html#csv.writer




回答2:


No need to use the csv module since the ',' in the first column is already part of your data, this will work:

with open('myfile.csv', 'w') as f:
    for row in data:
        f.write(', '.join(row))
        f.write('\n')



回答3:


You could try the below.

Code:

import csv
import re
with open('infile.csv', 'r') as f:
    lst = []
    for line in f:
        lst.append(re.findall(r',?(\S+)', line))
    with open('outfile.csv', 'w', newline='') as w:
        writer = csv.writer(w)
        for row in lst:
            writer.writerow(row)

Output:

A,B,C
"a1,a2",b1,c1
"a2,a4",b3,ct


来源:https://stackoverflow.com/questions/27098261/separate-data-with-a-comma-csv-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!