Home > Backend Development > Python Tutorial > How to Export a Nested Python List to a CSV File?

How to Export a Nested Python List to a CSV File?

Mary-Kate Olsen
Release: 2024-11-10 06:54:02
Original
1020 people have browsed it

How to Export a Nested Python List to a CSV File?

Exporting a Nested Python List to a CSV File

Need a quick and efficient way to transform a Python list of lists into a CSV file? Dive right into this solution:

import csv

# Sample list of lists
a = [[1.2, 'abc', 3], [1.2, 'werew', 4], [1.4, 'qew', 2]]

# Open the output CSV file for writing
with open('out.csv', 'w', newline='') as f:
Copy after login

Next, leverage the csv module's writer function to do the heavy lifting:

    # Create a writer object
    writer = csv.writer(f)

    # Write the rows to the file
    writer.writerows(a)
Copy after login

And voila! Your nested list will be neatly written to the out.csv file in the desired format:

1.2,abc,3
1.2,werew,4
1.4,qew,2
Copy after login

Enjoy the power of Python and CSV for your data manipulation tasks!

The above is the detailed content of How to Export a Nested Python List to a CSV File?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template