Python Write CSV

In Python, writing data to a CSV file can be done using the csv.writer() method, which allows you to write rows to a CSV file. Additionally, Python offers the DictWriter class for writing dictionaries to CSV files.

Writing to a CSV File Using csv.writer()

The csv.writer() method creates a writer object that you can use to write rows of data. You can use the writerow() method to write a single row or writerows() to write multiple rows at once.

Example:

import csv

# Data to be written to CSV
data = [
    ['Name', 'Age', 'City'],
    ['John', 25, 'New York'],
    ['Anna', 30, 'Paris'],
    ['Mike', 22, 'London']
]

# Writing to a CSV file
with open('output.csv', mode='w', newline='') as file:
    writer = csv.writer(file)

    # Writing a single row (header)
    writer.writerow(data[0])

    # Writing multiple rows (the rest of the data)
    writer.writerows(data[1:])

Explanation:

• csv.writer(file) creates a writer object to write to the specified file.

• writer.writerow(data[0]) writes the header row to the CSV file.

• writer.writerows(data[1:]) writes all the remaining rows from the data list.

Writing CSV File Using DictWriter

The csv.DictWriter class allows writing dictionaries to a CSV file, where each dictionary represents a row, and the keys of the dictionary are the column headers.

Example of Writing a CSV File with DictWriter

import csv

# Data to be written to CSV as dictionaries
data = [
    {'Name': 'John', 'Age': 25, 'City': 'New York'},
    {'Name': 'Anna', 'Age': 30, 'City': 'Paris'},
    {'Name': 'Mike', 'Age': 22, 'City': 'London'}
]

# Writing to a CSV file
with open('output_dict.csv', mode='w', newline='') as file:
    # Specify the fieldnames (column headers)
    fieldnames = ['Name', 'Age', 'City']

    # Create a DictWriter object
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    # Write the header row
    writer.writeheader()

    # Write the rows of data
    writer.writerows(data)

Explanation:

• csv.DictWriter(file, fieldnames=fieldnames) creates a writer object that uses dictionary keys as fieldnames (column headers).

• writer.writeheader() writes the header row to the CSV file.

• writer.writerows(data) writes the data, where each dictionary corresponds to a row in the CSV file.

Dialect in CSV Writing

Dialects are constructs that allow you to specify how CSV files should be formatted. They help customize the CSV file by defining attributes like the delimiter, quote character, and line terminator.

Common Dialect Attributes:

delimiter: Character used to separate fields (default is ,).

quotechar: Character used to quote fields containing special characters.

lineterminator: Defines how the lines in the CSV file are terminated (default is \r\n).

Example Using Dialects

import csv

# Data to be written
data = [
    ['Name', 'Age', 'City'],
    ['John', 25, 'New York'],
    ['Anna', 30, 'Paris'],
    ['Mike', 22, 'London']
]

# Define a custom dialect
csv.register_dialect('custom_dialect', delimiter=';', quotechar='"', lineterminator='\n')

# Writing to CSV using a custom dialect
with open('output_dialect.csv', mode='w', newline='') as file:
    writer = csv.writer(file, dialect='custom_dialect')

    writer.writerows(data)

In this example, we register a custom dialect that uses a semicolon (;) as the delimiter, double quotes (") as the quote character, and a newline (\n) as the line terminator.