gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
python code that converts list to csv
- User
python code that converts list to csv
- Assistant
You can use the csv module in Python to convert a list to a CSV file. Here's an example code:
import csv def list_to_csv(data, filename): with open(filename, 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerows(data) # Example usage data = [ ['Name', 'Age', 'Country'], ['John', '25', 'USA'], ['Jane', '30', 'Canada'] ] list_to_csv(data, 'output.csv')In this code, the
list_to_csvfunction takes two parameters:data(the list to be converted) andfilename(the name of the output CSV file). The function opens the file in write mode and creates acsv.writerobject. Then, thewriterowsmethod is used to write each row from the input list to the CSV file. Finally, an example usage is provided, where a sample data list is passed to thelist_to_csvfunction, and the output is saved to a file called 'output.csv'.