0

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.

4
  • what does your actual list look like? Is each row a string? Commented Nov 24, 2014 at 5:16
  • @DavidMarx Yes. It looks like this ['A','B','C']['a1,a2','b1','c1']['a2,a4','b3','ct'] Commented Nov 24, 2014 at 5:18
  • @vanandy what's your expected output? Commented Nov 24, 2014 at 5:36
  • @AvinashRaj Just to write to a csv file with correct headers and correct corresponding column data. Commented Nov 24, 2014 at 5:38

3 Answers 3

2

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/library/csv.html#csv.writer

Sign up to request clarification or add additional context in comments.

7 Comments

The filemode should be 'wb' now w... (and you can also use writer.writerows(data) to avoid the explicit for loop)
how you get the data list like above from the csv file?
@AvinashRaj If I understand your question correctly, with the csv.reader class.
@DavidMarx Thank you. But my data is like ['A','B','C']['a1,a2','b1','c1']['a2,a4','b3','ct'] and is not a list of lists like you mentioned in your answer, if that'd make a difference because that didn't work for me.
@vanandy is it a string?
|
0

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')

Comments

0

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

1 Comment

what do you need sys for?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.