Python: Write list of lists to CSV

折月煮酒 提交于 2021-02-05 07:01:10

问题


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..


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/60625652/python-write-list-of-lists-to-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!