Convert a List to CSV in Python

  • Post category:List

Converting a list to a CSV (Comma-Separated Values) file in Python can be achieved using the csv module. Here are two examples:

Example 1:

import csv

data = [['Name', 'Age', 'Country'],
        ['John', 25, 'USA'],
        ['Alice', 30, 'Canada'],
        ['Bob', 35, 'UK']]

with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

print("CSV file created successfully.")

Output:

CSV file created successfully.

Example 2:

import csv

fruits = ['apple', 'banana', 'orange']

with open('fruits.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(fruits)

print("CSV file created successfully.")

Output:

CSV file created successfully.