简体   繁体   中英

Python: Write list of lists to CSV

In my python script I'm having a list that has the following structure:

['00:00', 'abc', '2', 'xyz']
['00:01', 'cde', '3', 'sda']

and so on. I want to write this list to csv file in a way that every element is in separate row and every string in one element is in separate column. So I want to end up with the following result in csv file:

     A     |     B    |     C    |     D
1  00:00   |    abc   |     2    |    xyz     
2  00:01   |    xyz   |     3    |    sda

Currently I have a code like this:

with open('test1.csv',mode='w',encoding='UTF-8') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    for x in data:
        wr.writerow(x)

and the result I get is that every element of the list is written to column A, so it looks like this:

             A               |       
1  '00:00','abc','2','xyz'   |

How can I achieve splitting each string to separate column in csv file?

--edit

If I run the code from the first three answers I get the same result(except for the delimeter):

在此处输入图片说明

But my idea it to get 00:00 in column A, -6 in column B and so on..

How each list appears in CSV file depends on what data structure data is.

For data to be a list of lists, following code should work fine.

import csv

data = []
d1 = ['00:00', 'abc', '2', 'xyz']
d2 = ['00:01', 'cde', '3', 'sda']

data.append(d1)
data.append(d2)

with open('results_file.csv', mode='w') as results_file:
    results_writer = csv.writer(results_file, delimiter='|', quotechar='"', 
        quoting=csv.QUOTE_MINIMAL)
    results_writer.writerow(['A','B','C','D'])
    for x in data:
        results_writer.writerow(x)

results_file.csv looks like:

A|B|C|D
00:00|abc|2|xyz
00:01|cde|3|sda

How about a pandas approach? Nice and simple ...

import pandas as pd

data = [['00:00', 'abc', '2', 'xyz'], ['00:01', 'cde', '3', 'sda']] 
cols = ['A', 'B', 'C', 'D']

# Load data into a DataFrame.
df = pd.DataFrame(data, columns=cols)
# Write the CSV.
df.to_csv('output.csv', sep='|', index=False)

Per the docs you can change the separator using the sep parameter.

[Edited] Output:

Content of output.csv as shown from the console:

user@host ~/Desktop/so
$ cat output.csv
A|B|C|D
00:00|abc|2|xyz
00:01|cde|3|sda

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