Reputation: 3
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?
Upvotes: 0
Views: 2340
Reputation: 15990
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.
Upvotes: 1
Reputation: 7944
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
Upvotes: 0