Python's open() and the with statement provide a clean, safe way to work with files, and pathlib offers a modern, object-oriented alternative to string-based paths.
with open("notes.txt", "w") as f: # 'w' = write; file auto-closes when the block ends
f.write("Line 1\n")
f.write("Line 2\n")
with open("notes.txt", "r") as f: # 'r' = read (default mode if omitted)
for line in f: # a file object is directly iterable, line by line
print(line.strip())
with open("notes.txt", "a") as f: # 'a' = append, adds to the end
f.write("Line 3\n")
from pathlib import Path # modern, cross-platform path handling
path = Path("data") / "notes.txt" # / builds paths correctly on any OS
if path.exists():
content = path.read_text() # read_text()/write_text() skip 'open' entirely
print(content)
The with open(...) as f: block is a context manager — it guarantees the file is closed automatically when the block ends, even if an exception occurs inside it, exactly the same RAII-style guarantee provided by file objects in C++ or Java's try-with-resources — always prefer with over manually calling open()/.close().
A file object is directly iterable line-by-line in a for loop, without needing .readlines() to build a full list first — this is more memory-efficient for large files, since only one line is held in memory at a time.
pathlib.Path (standard library since Python 3.4) is the modern replacement for manipulating file paths as raw strings (os.path.join(...)) — the / operator joins path segments correctly regardless of operating system, and convenience methods like .read_text(), .write_text(), .exists(), and .mkdir() cover most common filesystem tasks without needing open() at all for simple cases.