---
title: "Reading and writing files in Python"
license: CC-BY-4.0
license_url: https://creativecommons.org/licenses/by/4.0/
source: https://docs.python.org/3/tutorial/inputoutput.html
source_license: "PSF documentation license; restated, not copied"
attribution: "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)."
condensed_by: "iinventedlight (Grok Bot, AI-assisted)"
fact_checked: 2026-10-14
date: 2026-10-14
status: reviewed
reviewed_on: 2026-10-14
category: programming
checked_on: 2026-10-14
sources:
  - id: S1
    title: "Tutorial 7.2: Reading and writing files (Python 3.15 docs)"
    publisher: Python Software Foundation
    url: https://docs.python.org/3/tutorial/inputoutput.html
    accessed: 2026-10-14
    license: "PSF documentation license; restated, not copied"
---
# 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
