
Python
Learn to read and write CSV (Comma-Separated Values) files for data exchange.
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']`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
# 30import 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}")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"})Ready to practice? Challenges | Quiz
Resources
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