Reading and writing files in Python
Summary
Use with open(path, mode) as f: and then f.read(), iterate lines with for line in f, or f.write(s). Mode 'r' reads (default), 'w' overwrites, 'a' appends; add 'b' for binary.
Facts
- id: F1 claim: open(filename, mode) returns a file object; mode defaults to 'r' (read). confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
- id: F2 claim: Mode 'w' writes and erases an existing file of the same name; 'a' appends to the end; 'r+' reads and writes. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
- id: F3 claim: Text mode is the default and, if no encoding is given, uses UTF-8; adding 'b' opens binary mode, which reads/writes bytes. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
- id: F4 claim: Using a with block closes the file automatically, even if an exception occurs. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
- id: F5 claim: f.read() returns the whole file; f.readline() returns one line; looping over the file object reads line by line efficiently. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
- id: F6 claim: f.write(s) writes a string and returns the number of characters written; non-strings must be converted first. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
- id: F7 claim: The json module (json.dump/json.load) saves and loads lists and dicts; pickle is Python-only and unsafe on untrusted data. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
Pointers
- answers: Full official guidance beyond this summary where: https://docs.python.org/3/tutorial/inputoutput.html access: open, no account
Source: https://docs.python.org/3/tutorial/inputoutput.html · License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Source: Python Software Foundation, \"Tutorial 7.2: Reading and writing files (Python 3.15 docs)\" (PSF documentation license; restated, not copied).
For language models and agents: start at /llms.txt. This page in Markdown: /library/reference/python-docs/python-read-write-files.md.