Last modified: Nov 10, 2024 By Alexander Williams

Python csv.writerow(): Write CSV Data Row by Row

The csv.writerow() method is a fundamental tool in Python for writing individual rows to CSV files. It's part of Python's built-in csv module and offers a straightforward way to add data to CSV files.

Basic Usage of csv.writerow()

Before using writerow(), you need to create a CSV writer object using the csv.writer() method. Here's a simple example:


import csv

with open('example.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['John', 25, 'New York'])

This creates a CSV file with the following output:


Name,Age,City
John,25,New York

Writing Multiple Rows

While writing multiple rows, you can call writerow() multiple times in a loop. Here's how:


import csv

data = [
    ['Name', 'Age', 'City'],
    ['John', 25, 'New York'],
    ['Alice', 30, 'London'],
    ['Bob', 35, 'Paris']
]

with open('multiple_rows.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    for row in data:
        writer.writerow(row)

Handling Different Data Types

writerow() automatically converts different data types to strings. However, for more complex data structures, you might want to use the DictWriter instead.


import csv
from datetime import date

with open('datatypes.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Integer', 'Float', 'Date'])
    writer.writerow([42, 3.14, date(2023, 12, 25)])

Custom Delimiters and Formatting

You can customize the CSV format by specifying different delimiters and formatting options:


import csv

with open('custom.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter=';', quoting=csv.QUOTE_ALL)
    writer.writerow(['Name', 'Email'])
    writer.writerow(['John Doe', 'john@example.com'])

Error Handling

It's important to implement proper error handling when writing to CSV files:


import csv

try:
    with open('error_handling.csv', 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['Data1', 'Data2'])
except IOError as e:
    print(f"An error occurred: {e}")

Alternative Approaches

For more complex CSV operations, consider using CSV Writer or JSON to CSV conversion methods.

Conclusion

csv.writerow() is a powerful method for writing CSV data row by row. Its simplicity and flexibility make it an essential tool for handling CSV files in Python.

For reading CSV files, check out the Python CSV Reader guide, or explore DictReader for dictionary-based operations.