Working with CSV Files in Python

CSV (Comma-Separated Values) files are widely used for storing tabular data. Python’s built-in csv module provides powerful tools to read from and write to CSV files efficiently.

Key Features of the csv Module

Example 1: Reading a CSV File

import csv

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

Example 2: Writing to a CSV File

import csv

with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['Alice', 30, 'New York'])

Example 3: Using a Different Delimiter

import csv

with open('data.tsv', 'w', newline='') as tsvfile:
    writer = csv.writer(tsvfile, delimiter='\t')
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['Bob', 25, 'Chicago'])

Example 4: Reading CSV with DictReader

import csv

with open('data.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['Name'], row['Age'])

Example 5: Writing CSV with DictWriter

import csv

fields = ['Name', 'Age', 'City']
rows = [{'Name': 'John', 'Age': 40, 'City': 'Boston'}]

with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fields)
    writer.writeheader()
    writer.writerows(rows)

Example 6: Handling Quoting in CSV

import csv

with open('quotes.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
    writer.writerow(['Name', 'Quote'])
    writer.writerow(['Alice', 'Hello, "world"!'])

Example 7: Skipping Headers While Reading

import csv

with open('data.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    next(reader)  # skip header
    for row in reader:
        print(row)

Example 8: Reading Large CSV with Iterator

import csv

def read_large_csv(filename):
    with open(filename, newline='') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            yield row

for row in read_large_csv('large_data.csv'):
    print(row)

Example 9: Writing CSV with Custom Line Terminator

import csv

with open('custom_lines.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, lineterminator='\n\n')
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Eve', 22])

Example 10: Reading CSV with Specific Encoding

import csv

with open('data_utf8.csv', newline='', encoding='utf-8') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)