Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
📖 File Fundamentals📖 Reading Files Effectively✍️ Writing Files Correctly🗂️ Working with File Paths🤝 Context Managers & Safety📊 CSV Data Processing🔄 JSON Parsing & Serialization🔐 Binary Files & Encoding⚙️ Performance & Best Practices
Python/File Io/Working With Csv

📊 CSV Data Processing — Structured Data Files

Learn to read and write CSV (Comma-Separated Values) files for data exchange.


🎯 Reading CSV Files

Use the `csv` module to parse CSV data easily.

import csv

# Read CSV file
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)  # Each row is a list

# File contents:
# Name,Age,City
# Alice,30,New York
# Bob,25,Los Angeles
#
# Output:
# ['Name', 'Age', 'City']
# ['Alice', '30', 'New York']
# ['Bob', '25', 'Los Angeles']

💡 Using DictReader for Named Columns

`DictReader` treats first row as column names.

import csv

with open("users.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)  # Each row is a dictionary
        print(row["Name"])  # Access by column name
        print(row["Age"])

# Output:
# {'Name': 'Alice', 'Age': '30', 'City': 'New York'}
# Alice
# 30

🎨 Real-World Example: Processing Sales Data

import csv

# Read sales data and calculate totals
total_sales = 0
product_count = {}

with open("sales.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        product = row["Product"]
        amount = float(row["Amount"])

        total_sales += amount
        product_count[product] = product_count.get(product, 0) + 1

print(f"Total sales: ${total_sales:.2f}")
print(f"Products sold: {product_count}")

📊 Writing CSV Files

import csv

# Write to CSV
data = [
    ["Name", "Age", "City"],
    ["Alice", 30, "New York"],
    ["Bob", 25, "Los Angeles"]
]

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

# Using DictWriter
with open("users.csv", "w") as file:
    fieldnames = ["Name", "Age", "City"]
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({"Name": "Alice", "Age": 30, "City": "New York"})
    writer.writerow({"Name": "Bob", "Age": 25, "City": "Los Angeles"})

🔑 Key Takeaways

  • ✅ Use `csv.reader()` for simple row access
  • ✅ Use `csv.DictReader()` for named columns
  • ✅ `DictWriter` for writing structured data
  • ✅ First row can be headers or data
  • ✅ Perfect for Excel-compatible files

Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn