Python: Write list of lists to CSV

Tags: , ,



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):

enter image description here

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

Answer

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


Source: stackoverflow