Mastering CSV File Handling in Python

Python

Introduction

CSV (Comma-Separated Values) is one of the most common file formats for handling tabular data. Python’s built-in csv module makes reading, writing, and editing CSV files straightforward and efficient.

Reading a CSV File

Use csv.reader to read a CSV file line by line:

import csv

with open('data.csv', newline='') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Writing to a CSV File

You can write rows to a CSV file using csv.writer:

import csv

data = [['Name', 'Score'], ['Alice', 90], ['Bob', 85]]

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

Using DictReader and DictWriter

If your CSV files have headers, DictReader and DictWriter are great tools.

import csv

# Reading with DictReader
with open('data.csv', newline='') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row['Name'], row['Score'])

# Writing with DictWriter
with open('output.csv', 'w', newline='') as file:
    fieldnames = ['Name', 'Score']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Name': 'Alice', 'Score': 90})

Handling Delimiters

You can change the delimiter if your CSV uses something other than a comma:

csv.reader(file, delimiter=';')

Conclusion

The csv module is a powerful way to handle structured data in Python. From simple tables to complex configurations, understanding CSV handling is essential for data-driven development.

Related Links

Python File Handling Basics: Reading, Writing, and Using with
IntroductionWorking with files is a common task in many Python projects—whether it's reading configuration files, saving...
How to Use enumerate() and zip() in Python
IntroductionWhen working with sequences in Python, efficient iteration can save both time and lines of code. Two powerfu...

Comment

Copied title and URL