CSV (Comma-Separated Values) is a text format for storing tabular data. It opens in Excel and Google Sheets and is used for data export and import.
name,age,balance
Alice,25,1000
Bob,30,500
import csv
Core functions: csv.writer(), csv.reader(), csv.DictWriter(), csv.DictReader().
Writing: csv.writer()
import csv
data = [
["name", "age", "balance"],
["Alice", 25, 1000],
["Bob", 30, 500],
["Charlie", 22, 2000]
]
with open("users.csv", "w", encoding="utf-8", newline='') as file:
writer = csv.writer(file)
writer.writerows(data) # write all rows at once
writerow() — write a single row, writerows() — write multiple rows.
with open("accounts.csv", "w", encoding="utf-8", newline='') as file:
writer = csv.writer(file)
writer.writerow(["name", "balance", "status"]) # headers
writer.writerow(["Alice", 1000, "active"])
writer.writerow(["Bob", 500, "blocked"])
Reading: csv.reader()
import csv
with open("users.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
for row in reader:
print(row) # each row is a list of strings
Skip the header row:
with open("users.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
next(reader) # skip the first row
for row in reader:
name = row[0]
age = int(row[1])
balance = int(row[2])
print(f"{name}: {age} years old, balance {balance}")
Working with Dicts: DictWriter and DictReader
Writing:
import csv
accounts = [
{"name": "Alice", "balance": 1000, "currency": "USD"},
{"name": "Bob", "balance": 500, "currency": "EUR"},
]
with open("accounts.csv", "w", encoding="utf-8", newline='') as file:
fields = ["name", "balance", "currency"]
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader() # write headers
writer.writerows(accounts)
Reading:
with open("accounts.csv", "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['name']}: {row['balance']} {row['currency']}")
Each row is a dictionary. Keys are column names, values are row data.
Example: Exporting Transactions
import csv
class BankAccount:
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
self.transactions = []
def deposit(self, amount):
self.balance += amount
self.transactions.append({"type": "deposit", "amount": amount, "balance": self.balance})
def withdraw(self, amount):
if amount > self.balance:
return False
self.balance -= amount
self.transactions.append({"type": "withdraw", "amount": amount, "balance": self.balance})
return True
def export_transactions(self, filename):
with open(filename, "w", encoding="utf-8", newline='') as file:
writer = csv.DictWriter(file, fieldnames=["type", "amount", "balance"])
writer.writeheader()
writer.writerows(self.transactions)
print(f"Transactions exported to {filename}")
account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200)
account.export_transactions("alice_transactions.csv")
Result alice_transactions.csv:
type,amount,balance
deposit,500,1500
withdraw,200,1300
Delimiters
By default, CSV uses a comma. You can change it:
# Semicolon
writer = csv.writer(file, delimiter=';')
# Tab
writer = csv.writer(file, delimiter='\t')
Best Practices
- Always specify
encoding="utf-8"for non-ASCII characters - When writing, always pass
newline=''— otherwise you’ll get extra blank lines - Use
DictWriter/DictReader— no need to remember column order - Wrap file reads in
try/except FileNotFoundError - Call
writeheader()beforewriterows()
Summary: csv.writer/reader — for simple lists; csv.DictWriter/DictReader — when working with dictionaries is more convenient.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!