๐Ÿ“ Python

CSV: Working with Tables

P
Author
PyLand Team
๐Ÿ“…
Published
03.04.2026
โฑ๏ธ
Reading time
2 min
๐Ÿ‘๏ธ
Views
435
๐ŸŒฟ
Level
Medium

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() before writerows()

Summary: csv.writer/reader โ€” for simple lists; csv.DictWriter/DictReader โ€” when working with dictionaries is more convenient.

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

What is an ORM

ORM (Object-Relational Mapping) is a technology that lets you work with a database through Python...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 363
๐Ÿ“

JSON: Persisting Data

Goal: Learn to save and load data in JSON format.

๐Ÿ“… 03.04.2026 ๐Ÿ‘๏ธ 467
๐Ÿ“

OOP: Program Like a World Builder ๐ŸŒ

Imagine: you're building a zombie-apocalypse game. You need zombies, humans, weapons. Every zombie has a...

๐Ÿ“… 03.04.2026 ๐Ÿ‘๏ธ 413

Did you like the article?

Subscribe to our updates and be the first to receive new articles. Grow with PyLand!