90. Working with CSV Files

The csv module in Python allows you to easily read and write CSV files. Below are 10 Python code snippets demonstrating common tasks when working with CSV files.

1. Reading a CSV File

import csv

# Open the CSV file for reading
with open('data.csv', mode='r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

This snippet opens a CSV file and prints each row. The csv.reader is used to read the contents of the file.


2. Reading CSV File with Headers

import csv

# Open the CSV file for reading with headers
with open('data.csv', mode='r') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)

DictReader reads the CSV into dictionaries using the first row as the keys for the fields, making it easier to access by column name.


3. Writing Data to a CSV File

This snippet writes a list of lists to a CSV file. writerows writes multiple rows at once.


4. Writing Data with Headers

DictWriter is used for writing dictionaries into the CSV file, and writeheader() writes the column names.


5. Reading CSV File Line by Line

This reads and processes each row of the CSV file one at a time, making it memory-efficient for large files.


6. Skipping Header Row in CSV

The next(reader) skips the first row, which is usually the header row.


7. Handling Comma-Separated Values with Different Delimiters

If the CSV uses a delimiter other than a comma (like semicolon ;), you can specify it using the delimiter parameter.


8. Writing CSV Data with Custom Delimiter

You can use a custom delimiter, such as a semicolon ;, when writing to a CSV file.


9. Reading CSV with Encoding

When reading files with non-ASCII characters, you may need to specify an encoding like utf-8 to avoid encoding errors.


10. Handling Empty Rows in CSV Files

This ensures that empty rows are skipped by checking if the row is not empty before processing it.


These 10 code snippets show how to effectively work with CSV files in Python using the csv module for both reading and writing structured data. Whether dealing with headers, custom delimiters, or large datasets, these techniques make it easy to handle CSV files.

Last updated