Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

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

Post a Comment for "Python: Write List Of Lists To CSV"