python to csv
- User
python to csv
- Assistant
To export data from Python to a CSV file, you can use the
csvmodule. Here's an example of how you can do this:import csv data = [ ['Name', 'Age', 'City'], ['John', 30, 'New York'], ['Jane', 25, 'Los Angeles'], ['Alex', 35, 'London'] ] filename = 'data.csv' with open(filename, 'w', newline='') as file: writer = csv.writer(file) writer.writerows(data) print(f'{filename} has been created successfully.')In this example, the
datavariable represents the data that you want to export. It is a list of lists, where each inner list represents a row in the CSV file.The
filenamevariable holds the name of the CSV file you want to create. You can change it to suit your needs.The
with open(filename, 'w', newline='') as file:statement opens the file in write mode. Thenewline=''parameter ensures that newlines are handled correctly across platforms.The
csv.writer(file)creates a writer object to handle writing data to the CSV file.The
writer.writerows(data)method writes the data to the CSV file.Finally, the
printstatement informs you when the file has been created successfully.Make sure to replace the example data with your own data to save it to a CSV file.