🐍 Reading & Writing Files

files

Open & Read Entire File

Reads the whole file content as one string.

from pathlib import Path
 
path = Path("example.txt")
 
with path.open("r", encoding="utf-8") as f:
    content = f.read()
 
print(content)

Read File Line by Line

Iterating over the file object is memory-friendly.

from pathlib import Path
 
path = Path("example.txt")
 
with path.open("r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

Read All Lines Into a List

from pathlib import Path
 
path = Path("example.txt")
 
with path.open("r", encoding="utf-8") as f:
    lines = f.readlines()
 
print(lines)   # ['first line\n', 'second line\n', ...]

Write (Overwrite) a File

Mode “w” creates the file or overwrites existing content.

from pathlib import Path
 
path = Path("output.txt")
 
with path.open("w", encoding="utf-8") as f:
    f.write("Hello\n")
    f.write("Second line\n")

Append to a File

Mode “a” adds to the end of the file.

from pathlib import Path
 
path = Path("log.txt")
 
with path.open("a", encoding="utf-8") as f:
    f.write("New entry\n")

Read & Write (r+ / w+ / a+)

Combine reading and writing. Be careful with positions and overwriting.

from pathlib import Path
 
path = Path("data.txt")
 
with path.open("r+", encoding="utf-8") as f:
    content = f.read()
    f.seek(0)              # go back to start
    f.write("Header\n" + content)

Copy a File

Use shutil.copy2 to copy content + metadata (timestamps).

from pathlib import Path
import shutil
 
src = Path("example.txt")
dst = Path("backup") / "example_backup.txt"
 
shutil.copy2(src, dst)

Move or Rename a File

from pathlib import Path
import shutil
 
src = Path("example.txt")
dst = Path("archive") / "example.txt"
 
shutil.move(src, dst)

Delete a File

Path.unlink() is the modern way.

from pathlib import Path
 
path = Path("old_file.txt")
 
if path.exists():
    path.unlink()

Basic Exception Handling Around File I/O

Useful to avoid crashes if a file is missing.

from pathlib import Path
 
path = Path("maybe_exists.txt")
 
try:
    with path.open("r", encoding="utf-8") as f:
        print(f.read())
except FileNotFoundError:
    print("File not found")

Quick Mode Cheatsheet

  • “r”  → read (file must exist)

  • “w”  → write (truncate / create new)

  • “a”  → append

  • “r+” → read & write

  • “b”  → add to mode for binary (e.g. “rb”, “wb”)