File I/O
File I/O is reading and writing bytes or text on disk. open (or Path.open) returns a file object; with closes it. Mode and encoding decide whether you see str or bytes.
Detailed Explanation
open(path, mode="r", encoding=None) is the builtin. Mode "r" reads text, "w" truncates and writes text, "a" appends text, "x" writes only if the file does not exist. Add b for binary ("rb", "wb"). Add + for read-write. Text mode requires an encoding on platforms where the default is not what you want; pass encoding="utf-8" instead of hoping.
The return value is a file object. It is a context manager. with open(path, encoding="utf-8") as f: opens, binds, and closes. Closing flushes writes and releases the descriptor. Without with, a crash or an early return can lose buffered data. Do not rely on reference counting to close files.
Read methods: read() all, read(n) at most n characters or bytes, readline(), and iteration (for line in f) which is the memory-safe way to walk a large text file. Write methods: write(data) returns the number of characters or bytes written, writelines writes an iterable of chunks without adding newlines for you.
Text mode translates newlines. On Windows, "\n" in Python becomes "\r\n" on disk unless you pass newline="". Binary mode does no translation. Use binary for anything that is not actually text: images, zip files, pickled data.
pathlib.Path wrappers (read_text, write_text, read_bytes, write_bytes) cover the whole-file cases and still open under the hood. They are the readable default for small files. Streams, pipes, and partial reads stay with open.
Buffering is on by default. flush() pushes the buffer to the OS. os.fsync(f.fileno()) pushes the OS buffer to disk. Most programs need neither; a write-ahead log or a crash-safe replace needs both, plus writes to a temp file and os.replace.
Errors are exceptions: FileNotFoundError, PermissionError, IsADirectoryError. Catch the specific type. A missing file is not a permission problem.
Code Examples
from pathlib import Path
path = Path("cart.txt")
with path.open("w", encoding="utf-8") as out:
out.write("sku-1\n")
out.write("sku-2\n")
with path.open(encoding="utf-8") as inp:
lines = [line.strip() for line in inp]
print(lines) # ['sku-1', 'sku-2']# Binary: no encoding, no newline translation.
raw = Path("cart.txt").read_bytes()
print(raw[:5]) # b'sku-1'
Path("cart.bin").write_bytes(b"\x00\x01\x02")# Whole-file helpers for small text.
Path("note.md").write_text("# hello\n", encoding="utf-8")
print(Path("note.md").read_text(encoding="utf-8"))Common Gotchas
Forgetting `with` can lose the last writes
the buffer may not flush if the process dies. Always close, preferably with `with`.
`"w"` truncates immediately
opening an existing file for write erases it even if you never call `write`. Write to a temp file and replace when the content must be atomic.
Default encoding is platform-dependent
a file written on Linux as UTF-8 can fail to decode on a Windows install whose default is cp1252. Pass `encoding` every time.
Iterating a file walks lines
`for chunk in file` is not "arbitrary chunks". Use `read(n)` for blocks.