Separate Data With A Comma Csv Python
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 e
Solution 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 indata:
writer.writerow(row)
Solution 2:
No need to use the csv
module since the ',' in the first column is already part of your data, this will work:
withopen('myfile.csv', 'w') as f:
forrowin data:
f.write(', '.join(row))
f.write('\n')
Solution 3:
You could try the below.
Code:
import csv
import re
withopen('infile.csv', 'r') as f:
lst = []
for line in f:
lst.append(re.findall(r',?(\S+)', line))
withopen('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
Post a Comment for "Separate Data With A Comma Csv Python"