Python Lesson 7: Reading and Writing Files

📎 This article includes 3 downloadable practice files ↓

⏱ 2 min read

📘 Python Beginner Course · Lesson 7 of 12

In this article
  1. Reading a CSV
  2. Writing a CSV
  3. Encodings
  4. Paths
  5. Where beginners go wrong
  6. Practice

Most office data arrives as files: CSV exports from Tally, SAP or a website. Python reads them, does the work, and writes a result file, without opening Excel at all.

Reading a CSV

import csv
from collections import defaultdict

totals = defaultdict(float)                 # a dict that starts every new key at 0.0
with open("sales.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):           # each row is a dict: {"region": "North", "qty": "3", ...}
        totals[row["region"]] += int(row["qty"]) * float(row["rate"])
  • with open(...) as f: opens the file and closes it automatically afterwards.
  • DictReader uses the header row, so you refer to columns by name.
  • Everything read from CSV is text: convert with int() and float().

Writing a CSV

with open("region_totals.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f)
    w.writerow(["region", "sales"])
    for region in sorted(totals):
        w.writerow([region, round(totals[region])])

"w" creates or overwrites; "a" appends. newline="" stops blank lines appearing between rows on Windows.

⚠️ Opening a file with “w” wipes it immediately. Write results to a new file name, never over your source data.

Encodings

Files with ₹, Hindi text or names with accents need the right encoding. Use encoding="utf-8"; for CSVs saved by Excel as “CSV UTF-8”, use "utf-8-sig" to drop the invisible marker at the start. Old exports may be "cp1252".

Paths

from pathlib import Path
folder = Path(r"C:\Reports\2026")       # r"..." keeps backslashes literal
for f in folder.glob("*.csv"):
    print(f.name)

Relative names like “sales.csv” are looked up in the folder you run the script from.

💡 Plain text files work the same way: open(“notes.txt”, encoding=”utf-8″).read() reads everything; .readlines() gives a list of lines.

Where beginners go wrong

Error Cause
FileNotFoundError Running from a different folder; use full paths or cd first
UnicodeDecodeError Wrong encoding; try utf-8-sig or cp1252
PermissionError The file is open in Excel; close it
Totals as text joined together Forgot int()/float()

Practice

Download the script (and data file, if listed) below into one folder. Open a terminal in that folder and run python lesson-NN.py. Compare with the expected output, then change something and run it again: that’s how Python is learned.

📎 Practice files for this article

  • 🐍
    Lesson 7 scriptThe complete script from this lesson, tested.
    ⬇ PY · 629 B
  • 📄
    Expected outputWhat the script prints when you run it.
    ⬇ TXT · 121 B
  • 🧾
    sales.csv120 orders (July-September 2026) used by the scripts.
    ⬇ CSV · 7 KB

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong