0

every body. I have some data like the following:

data = [ ['234','123','145','134','156'],['12','67895','12345','1234'] ]

I want to write these data into a csv file in such a way that "aid,pid" are the column title. The first element of each sub-list is the "aid" column,the rest are the "pid".Now I want to write the pid with a tab character like the following.

aid,pid

234,123 145 134 156

12,67895 12345 1234

Here is my sample code

import csv

data =[ ['234','123','145','134','156'],['12','67895','12345','1234'] ]
valid_result = open('./result/valid_result.csv','wb')
writer = csv.writer(valid_result,delimiter = ',',dialect = 'excel-tab')
header = ['aid','pid']
writer.writerow(header)

for record in data:
    writer.writerow(record)

Is there any solution in python?

3
  • Yes, there are solutions, have you tried anything? There are several related questions about writing csv with python. Or is your question regarding breaking the list into two columns? Commented May 9, 2013 at 10:48
  • Google and try out something your self. If that does not work, provide the sample code here and tell us what error you are getting .. Commented May 9, 2013 at 10:54
  • I have found the solution by myself. Actually,the csv file ignores the tag character and replace it with empty char.For example,if I have the data = ['123','23214'+'\t'+'3244'],the real data input into the csv file is 123,232143244 ,after execute the code csv.writerow(data). How do you think of this situation?Or maybe my idea is wrong. Commented May 9, 2013 at 12:22

2 Answers 2

1

If I understand correctly, you need to split each of your lists into two columns:

for record in data:
    new_rec = [record[0], " ".join(record[1:])]

Something like this should do, and write new_rec instead of record.

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

Comments

0

Replace your for loop with this:

for record in data:
    writer.writerow([record[0],'\t'.join(record[1:])])

You will also have to close the file aftwewards via valid_result.close().

The following makes use of with and open which opens and closes the file for you:

import csv
data =[ ['234','123','145','134','156'],['12','67895','12345','1234'] ]
with open('valid_result.csv','wb') as valid_result:
    writer = csv.writer(valid_result,delimiter = ',',dialect = 'excel-tab')
    header = ['aid','pid']
    writer.writerow(header)
    for record in data:
        writer.writerow([record[0],'\t'.join(record[1:])])

Both produce:

aid,pid
234,123 145 134 156
12,67895    12345   1234

1 Comment

That should be '\t'.join(record[1:])

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.