Python · Module 8 · Lesson 11 min read

Reading & Writing Files

open() modes

ModeMeaning
"r"read (default); error if missing
"w"write, erases the existing content
"a"append to the end
"x"create, error if it already exists
"r+"read and write
add "b"binary (images, PDFs): "rb", "wb"

Always use with, so the file is closed automatically, and pass encoding="utf-8" for text so emojis and other languages work everywhere.

Reading

  • f.read() reads the whole file as one string.
  • for line in f: reads line by line, which uses little memory even for huge files.
  • f.readlines() returns a list of lines.

pathlib: the modern way

Python
from pathlib import Path
p = Path("notes.txt")
p.write_text("hi", encoding="utf-8")
p.read_text(encoding="utf-8")
p.exists(), p.suffix, p.parent

Paths join with /: Path("data") / "file.txt".

⚠️ Each line you read ends with \n. Use .strip() or .rstrip("\n").

▶️ Runs in the app (files live in the app's temporary memory).

Example

Python
from pathlib import Path

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Line 1\n")
    f.write("Line 2\n")

with open("notes.txt", "a", encoding="utf-8") as f:
    f.write("Line 3 (appended)\n")

with open("notes.txt", encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.strip())

p = Path("hello.txt")
p.write_text("Namaste 🙏", encoding="utf-8")
print(p.read_text(encoding="utf-8"))   # Namaste 🙏
print(p.exists(), p.suffix)            # True .txt