Writing a Python List of Lists to a CSV File

Writing a Python list of lists to a csv file

Python's built-in CSV module can handle this easily:

import csv

with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(a)

This assumes your list is defined as a, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to csv.writer() as documented in the library reference page linked above.

Update for Python 3

import csv

with open("out.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(a)

Python: Write list of lists to CSV

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

Scheme How to write list of lists into CSV file

The code in your question is for writing text to a file, nothing in it is specific for writing a CSV file. You'd need to parse the list contents, writing each sublist in a different line, separating the elements with commas.

But we don't need to reinvent the wheel, in Racket just install the csv-writing package - in case you can't find it, the raco command is in the bin folder where you installed Racket:

raco pkg install csv-writing

Now we can use it:

(require csv-writing)

(define (write-to-a-file lst path)
(call-with-output-file path
(lambda (output-port)
(display-table lst output-port))
#:exists 'replace))

Call your procedure like this:

(define lst '((1 2) (3 4) (5 6)))
(write-to-a-file lst "/path/to/file.csv")

The contents of file.csv will be:

1,2
3,4
5,6

How to write List of lists in csv file in python

This is trivial with the csv module:

with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)

You already have the header in data as the first row; you can write all rows in one go with the writer.writerows() method. That's all there is to it, really.

List of lists to csv with commas to separate fields and newlines to separate rows

You should use writerows instead of writerow.

import csv

test=[['a','1','!'],['b','2','?']]

with open('./csv_files/CtMLI.csv', 'w', newline="\n") as myfile:
wr = csv.writer(myfile)
wr.writerows(test)

Write list of lists to CSV file. Putting sub-lists into individual columns

Use following code snippet:

import pandas as pd
cols = ['a', 'b', 'c', 'd']
d = [dict(zip(cols, vals)) for vals in results]
pd.DataFrame(d).to_csv('C:\Users\out.csv')

In case you want to append to existing csv file, change last line to:

pd.DataFrame(d).to_csv('C:\Users\out.csv', mode='a', header=False)

This is how your dataframe looks:

    a   b   c          d
0 11 22 33 [1, 2, 3]
1 44 55 66 [4, 5, 6]

Write Python list of lists row wise to a csv file

You need to unpack each row into a flat list.

import csv

my_list = [
[[1.75], [4.75]],
[[2.5], [2.5]],
[[3.5], [3.5]],
[[4.0], [4.0]],
]

with open("my.csv", "w") as f:
writer = csv.writer(f)

for row in my_list:
writer.writerow([l[0] for l in row])

Or if preferred, the for loop could be replaced with a generator expression so that you can use writerows as you are currently doing:

    writer.writerows([l[0] for l in row] for row in my_list)

Export a list of lists to CSV file

You should be able to use the writerows function of the csvwriter class to do this all at once without a loop.

with open("testFile.csv", "w") as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerows(listOfRows)


Related Topics



Leave a reply



Submit