Categories
Python Answers

How to write a Python list of lists to a CSV file?

Spread the love

Sometimes, we want to write a Python list of lists to a CSV file.

In this article, we’ll look at how to write a Python list of lists to a CSV file.

How to write a Python list of lists to a CSV file?

To write a Python list of lists to a CSV file, we can use the csv module.

For instance, we write:

import csv

a = [[1.2, 'abc', 3], [1.2, 'werew', 4], [1.4, 'qew', 2]]

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

to pass the nested list a as the argument of writer.writerows to write the file to the out.csv file.

We open the out.csv file with 'w' permission to let us write to the file.

And we set the new line character to an empty string as specified with newline="".

Then we call csv.writer with f to create the writer object and call writerows to write to the file.

Therefore, out.csv has:

1.2,abc,3
1.2,werew,4
1.4,qew,2

Conclusion

To write a Python list of lists to a CSV file, we can use the csv module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *