Goal: Learn to read and write tabular data in CSV format.
🤔 What Is CSV?
CSV (Comma-Separated Values) is a text file format for storing tabular data.
Example CSV file:
name,age,balance
Алиса,25,1000
Боб,30,500
Чарли,22,2000
How it looks in Excel:
| name | age | balance |
|------|-----|---------|
| Алиса | 25 | 1000 |
| Боб | 30 | 500 |
| Чарли | 22 | 2000 |
Features:
- ✅ Simple text format
- ✅ Opens in Excel, Google Sheets
- ✅ Used for data export/import
- ✅ Built-in Python support!
📝 Importing the CSV Module
import csv
Main functions:
- csv.writer() — write CSV
- csv.reader() — read CSV
- csv.DictWriter() — write with dicts
- csv.DictReader() — read with dicts
💾 Writing CSV — csv.writer()
Basic Writing
import csv
# Data to write
data = [
["name", "age", "balance"],
["Алиса", 25, 1000],
["Боб", 30, 500],
["Чарли", 22, 2000]
]
# Write to file
with open("users.csv", "w", encoding="utf-8", newline='') as file:
writer = csv.writer(file)
writer.writerows(data) # Write all rows at once
print("CSV file created!")
What happens:
1. csv.writer(file) — create a writer object
2. writerows(data) — write all rows at once
3. File users.csv is created!
Result (users.csv):
name,age,balance
Алиса,25,1000
Боб,30,500
Чарли,22,2000
Writing Row by Row
import csv
with open("accounts.csv", "w", encoding="utf-8", newline='') as file:
writer = csv.writer(file)
# Headers
writer.writerow(["name", "balance", "status"])
# Data
writer.writerow(["Алиса", 1000, "active"])
writer.writerow(["Боб", 500, "blocked"])
print("Done!")
writerow() — write one row
writerows() — write multiple rows
📂 Reading CSV — csv.reader()
import csv
with open("users.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
for row in reader:
print(row)
# Output:
# ['name', 'age', 'balance']
# ['Алиса', '25', '1000']
# ['Боб', '30', '500']
# ['Чарли', '22', '2000']
What happens:
- csv.reader(file) — create a reader
- Each row is a list of strings
- The first row contains headers
Skipping Headers
import csv
with open("users.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
next(reader) # Skip the first row (headers)
for row in reader:
name = row[0]
age = int(row[1])
balance = int(row[2])
print(f"{name}: {age} years old, balance {balance}")
# Output:
# Алиса: 25 years old, balance 1000
# Боб: 30 years old, balance 500
# Чарли: 22 years old, balance 2000
next(reader) — read and skip one row.
📚 Working with Dicts — DictWriter/DictReader
Writing with Dicts — csv.DictWriter()
import csv
accounts = [
{"name": "Алиса", "balance": 1000, "currency": "RUB"},
{"name": "Боб", "balance": 500, "currency": "USD"},
{"name": "Чарли", "balance": 2000, "currency": "RUB"}
]
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) # Write data
print("CSV created!")
Advantages:
- ✅ Works with dicts (more convenient)
- ✅ No need to remember column order
- ✅ Automatic headers
Reading with Dicts — csv.DictReader()
import csv
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']}")
# Output:
# Алиса: 1000 RUB
# Боб: 500 USD
# Чарли: 2000 RUB
Each row is a dict!
- Keys — column names
- Values — data from the row
🎯 Example: Exporting Bank Transactions
import csv
class BankAccount:
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
self.transactions = []
def deposit(self, amount):
"""Deposit money."""
self.balance += amount
self.transactions.append({
"type": "deposit",
"amount": amount,
"balance": self.balance
})
def withdraw(self, amount):
"""Withdraw money."""
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):
"""Export transactions to CSV."""
with open(filename, "w", encoding="utf-8", newline='') as file:
fields = ["type", "amount", "balance"]
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader()
writer.writerows(self.transactions)
print(f"Transactions exported to {filename}")
# Usage
account = BankAccount("Алиса", 1000)
account.deposit(500)
account.withdraw(200)
account.deposit(300)
account.export_transactions("alice_transactions.csv")
Result (alice_transactions.csv):
type,amount,balance
deposit,500,1500
withdraw,200,1300
deposit,300,1600
🎯 Example: Exporting All Bank Accounts
import csv
class Bank:
def __init__(self):
self.accounts = []
def create_account(self, name, balance=0):
"""Create an account."""
account = {"name": name, "balance": balance}
self.accounts.append(account)
def export_all_accounts(self, filename):
"""Export all accounts to CSV."""
with open(filename, "w", encoding="utf-8", newline='') as file:
fields = ["name", "balance"]
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader()
writer.writerows(self.accounts)
print(f"All accounts exported to {filename}")
# Usage
bank = Bank()
bank.create_account("Алиса", 1000)
bank.create_account("Боб", 500)
bank.create_account("Чарли", 2000)
bank.export_all_accounts("bank_accounts.csv")
Result (bank_accounts.csv):
name,balance
Алиса,1000
Боб,500
Чарли,2000
🛡️ Safe CSV Reading
import csv
def load_accounts_from_csv(filename):
"""Load accounts from CSV."""
accounts = []
try:
with open(filename, "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
try:
account = {
"name": row["name"],
"balance": float(row["balance"])
}
accounts.append(account)
except (KeyError, ValueError) as e:
print(f"Error in row: {row}. Skipping.")
print(f"Loaded {len(accounts)} accounts")
return accounts
except FileNotFoundError:
print("File not found!")
return []
# Usage
accounts = load_accounts_from_csv("bank_accounts.csv")
for account in accounts:
print(f"{account['name']}: {account['balance']}")
📊 Using Delimiters
By default, CSV uses a comma ,, but you can change it:
Semicolon (;)
import csv
data = [["name", "balance"], ["Алиса", 1000]]
with open("data.csv", "w", encoding="utf-8", newline='') as file:
writer = csv.writer(file, delimiter=';')
writer.writerows(data)
# Result: name;balance
Tab (\t)
writer = csv.writer(file, delimiter='\t')
⚡ Best Practices
✅ Do:
- Use
encoding="utf-8"for non-ASCII characters - Use
newline=''when writing - Use DictWriter/DictReader for convenience
- Wrap file reads in try/except
- Validate data when reading
❌ Don’t:
- Don’t forget headers (
writeheader()) - Don’t mix delimiters
- Don’t ignore errors when reading
🎓 Summary
CSV is:
- ✅ A tabular data format
- ✅ Opens in Excel
- ✅ Simple export/import
- ✅ Built-in Python support
Main functions:
- csv.writer() → write lists
- csv.reader() → read lists
- csv.DictWriter() → write dicts
- csv.DictReader() → read dicts
Golden rule: Use DictWriter/DictReader for dict-based work — it’s more convenient and readable!
🔗 Related Topics
Now you can export data to Excel! 📊✨
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!