简体   繁体   中英

write csv file with special format in python

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM