How to Convert a List to a CSV File in Python?

Estimated read time 2 min read

To convert a list to a CSV (Comma Separated Values) file in Python, you can use the built-in csv module. Here’s an example code snippet that demonstrates how to do this:

import csv

def list_to_csv(lst, filename):
    with open(filename, 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerows(lst)

# Example usage
my_list = [['Name', 'Age', 'City'],
           ['John', 25, 'New York'],
           ['Alice', 30, 'London'],
           ['Bob', 35, 'Paris']]

list_to_csv(my_list, 'output.csv')

In this example, we define a function called list_to_csv that takes a list (lst) and a filename as input parameters. It opens the specified file in write mode using the open function and creates a csv.writer object. The writerows method of the csv.writer object is then used to write each row of the list to the CSV file.

In the example usage section, we create a sample list called my_list containing some data. We then call the list_to_csv function with my_list as the input and provide the desired filename as 'output.csv'.

After executing the code, a CSV file named output.csv will be created in the same directory as your Python script, containing the data from the list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply