Reading and Writing CSV Files in Python

CSV (Comma-Separated Values) files are widely used for data storage and exchange. In Python, you can easily read from and write to CSV files using the built-in csv module. This article will guide you through the basics of working with CSV files in Python.

Reading CSV Files

To read a CSV file, you can use the csv.reader class from the csv module. Here’s a simple example:

import csv

# Open the CSV file
with open('example.csv', mode='r') as file:
    reader = csv.reader(file)
    
    # Iterate over each row in the CSV
    for row in reader:
        print(row)

In this example, example.csv is opened in read mode, and csv.reader is used to parse the file. Each row of the CSV file is printed as a list of values.

Writing CSV Files

To write data to a CSV file, use the csv.writer class. Here’s how you can write a list of rows to a CSV file:

import csv

# Data to be written to the CSV
data = [
    ['Name', 'Age', 'City'],
    ['Alice', 30, 'New York'],
    ['Bob', 25, 'Los Angeles'],
    ['Charlie', 35, 'Chicago']
]

# Open the CSV file in write mode
with open('output.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    
    # Write each row to the CSV file
    writer.writerows(data)

In this example, output.csv is created or overwritten with the specified data. The writer.writerows() method is used to write multiple rows at once.

Conclusion

Working with CSV files in Python is straightforward using the csv module. You can easily read from and write to CSV files, making it simple to handle data in this common format.