简体   繁体   中英

How to convert a list of tuples into different csv files

I have a list of tuples like this:

List=[ ('1',['45','55','56','57']) , ('2',['200','202','202']) , ('3',['500','501','502'])]

As can be seen, three tuples of size 2.

I want to convert this list into three different csv files.

The output should be three different csv file with the names of "1.csv","2.csv","3.csv"

While the files you want are valid CSV files, they're so trivial there's no need to use the csv module to create them (or read them).

data = [
    ('1', ['45', '55', '56', '57']),
    ('2', ['200', '202', '202']),
    ('3', ['500', '501', '502']),
    ]

for dataset_name, dataset in data:
    with open('{}.csv'.format(dataset_name), 'w') as outfile:
        for item in dataset:
            outfile.write('{}\n'.format(item))

This assumes each item in the lists should be on their own line.

If you want the data in one row:

List=[ ('1',['45','55','56','57']) , ('2',['200','202','202']) , ('3',['500','501','502'])]

for filename, data in List:
    with open('{}.csv'.format(filename), 'w') as f_output:
        f_output.write(','.join(data))

This would give you:

1.csv

45,55,56,57

2.csv

200,202,202

3.csv

500,501,502

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