Create a .csv file with values from a Python list

Learn create a .csv file with values from a python list with practical examples, diagrams, and best practices. Covers python, csv, xlrd development techniques with visual explanations.

Exporting Python List Data to a CSV File

Hero image for Create a .csv file with values from a Python list

Learn how to efficiently write data from Python lists into a Comma Separated Values (CSV) file, covering basic methods and the csv module for robust handling.

Creating a CSV file from data stored in Python lists is a common task in data processing and reporting. Whether you're dealing with simple lists of strings or complex lists of dictionaries, Python provides straightforward ways to achieve this. This article will guide you through the process, starting with basic file writing and progressing to using Python's built-in csv module for more structured and error-resistant output.

Basic CSV Creation: Manual String Formatting

For very simple cases, you can manually format your list data into a comma-separated string and write it directly to a file. This method is suitable when your data doesn't contain commas or other special characters that would complicate parsing. Each sub-list typically represents a row, and elements within a sub-list represent columns.

data = [
    ['Name', 'Age', 'City'],
    ['Alice', 30, 'New York'],
    ['Bob', 24, 'Los Angeles'],
    ['Charlie', 35, 'Chicago']
]

filename = 'simple_output.csv'

with open(filename, 'w', newline='') as file:
    for row in data:
        file.write(','.join(map(str, row)) + '\n')

print(f"'{filename}' created successfully using manual formatting.")

Example of writing a list of lists to a CSV file using manual string formatting.

Using Python's csv Module for Robust Output

Python's csv module is designed to handle CSV files correctly, including proper escaping of special characters. It provides csv.writer for writing data and csv.reader for reading. When writing, csv.writer takes care of quoting fields that contain delimiters, newlines, or quote characters, ensuring that your CSV file is correctly formatted and easily parsable by other applications.

flowchart TD
    A[Python List of Lists/Dictionaries] --> B{csv.writer object}
    B --> C["writer.writerow() for each row"]
    C --> D["Open CSV File (write mode)"]
    D --> E[Formatted CSV File]
    E --"Handles quoting & delimiters"--> F[External Application (e.g., Excel)]

Data flow for creating a CSV file using Python's csv module.

import csv

data_with_quotes = [
    ['Name', 'Age', 'City'],
    ['Alice', 30, 'New York, USA'],
    ['Bob', 24, 'Los Angeles'],
    ['Charlie', 35, 'Chicago "Windy City"']
]

filename = 'robust_output.csv'

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

print(f"'{filename}' created successfully using the csv module.")

Example of writing a list of lists to a CSV file using csv.writer and writerows.

Handling Lists of Dictionaries with csv.DictWriter

When your data is structured as a list of dictionaries, where each dictionary represents a row and its keys are column headers, csv.DictWriter is the most convenient tool. It automatically maps dictionary keys to column headers, making your code cleaner and less error-prone. You need to provide a fieldnames parameter, which is a list of strings corresponding to the dictionary keys you want as headers.

import csv

data_dicts = [
    {'Name': 'Alice', 'Age': 30, 'City': 'New York'},
    {'Name': 'Bob', 'Age': 24, 'City': 'Los Angeles'},
    {'Name': 'Charlie', 'Age': 35, 'City': 'Chicago'}
]

filename = 'dict_output.csv'
fieldnames = ['Name', 'Age', 'City'] # Order of headers

with open(filename, 'w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader() # Writes the header row
    writer.writerows(data_dicts)

print(f"'{filename}' created successfully using csv.DictWriter.")

Example of writing a list of dictionaries to a CSV file using csv.DictWriter.