Python CSV Module: Reading and Writing CSV Files ๐Ÿ“„

CSV file icon

Python CSV Module: Reading and Writing CSV Files ๐Ÿ“„

The csv module simplifies working with comma-separated values files. Let's explore its basic and advanced features with clear examples.

1. Reading Simple CSV Files

import csv

with open('data.csv', newline='', encoding='utf-8') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)  # ['Name', 'Age', 'Country']

2. Writing to a CSV File

import csv

data = [
    ['Name', 'Score', 'Remark'],
    ['Alice', '85', 'Pass'],
    ['Bob', '92', 'Excellent']
]

with open('results.csv', 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(data)

3. Using DictReader for Key-Value Reading

import csv

with open('data.csv', newline='', encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(f"{row['Name']} from {row['Country']} is {row['Age']} years old.")

4. Using DictWriter for Key-Value Writing

import csv

fields = ['Name', 'Age', 'Country']
rows = [
    {'Name': 'John Doe', 'Age': '29', 'Country': 'USA'},
    {'Name': 'Jane Smith', 'Age': '31', 'Country': 'Canada'}
]

with open('people.csv', 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fields)
    writer.writeheader()
    writer.writerows(rows)

Summary

  • Use csv.reader and csv.writer for basic row-based CSV processing.
  • DictReader and DictWriter offer key-value based CSV file handling.
  • Explicit UTF-8 encoding ensures safe handling of diverse character sets.

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“