TetSharing
Python tutorial · 22 chapters
  1. Get started
  2. Syntax and comments
  3. Variables
  4. Numbers and math
  5. Strings
  6. f-strings and formatting
  7. Booleans and logic
  8. if, elif, else
  9. Lists
  10. Tuples
  11. Dictionaries
  12. Sets
  13. for loops and range()
  14. while, break, continue
  15. Functions
  16. Default and keyword arguments
  17. Lambda and sorting keys
  18. List comprehensions
  19. Errors and exceptions
  20. Modules and imports
  21. Reading and writing files
  22. Classes and objects

Final Python quiz
Cheat sheet: python string methods
Cheat sheet: python lists dicts

Chapter 21 of 22 · By Ethan Cole · Updated November 21, 2026

Python File Handling: open(), with and pathlib

Programs become useful when they can keep data after they finish. The simplest way is a text file. Python's built-in open() returns a file object that you can read from or write to, and the with statement makes sure the file is closed properly.

Modes

The second argument of open() is the mode:

  • "r" reads (the default). The file must exist, or you get FileNotFoundError.
  • "w" writes, creating the file or erasing an existing one first.
  • "a" appends to the end, creating the file if needed.
  • Add b for binary data, as in "rb" for an image.

Always pass encoding="utf-8" for text. Without it, Python uses the operating system's default encoding, which differs between Windows and macOS and causes garbled characters.

The with statement

with open(...) as f: opens the file, gives you the object as f, and closes it automatically when the indented block ends, even if an exception happens inside. That matters because unclosed files may not have their data fully written. Prefer with over calling f.close() yourself.

Python 3 · editable

Expected output

1 first line
2 second line
3 third line
3 lines, 34 characters

The example writes two lines, appends a third with print(..., file=f), then reads the file back. When you run it in the browser, the file lives in Pyodide's in-memory file system and disappears when you leave the page.

Ways to read

  • Loop over the file object: for line in f: reads one line at a time, which works for files of any size. Each line keeps its trailing "\n", so strip it before printing.
  • f.read() returns the whole file as one string.
  • f.readlines() returns a list of lines.

f.write() does not add a newline for you; include "\n" yourself, or use print() with file=f, which does.

pathlib shortcuts

The pathlib module represents paths as objects. Path("notes.txt").read_text(encoding="utf-8") opens, reads and closes in one call, and write_text() does the reverse. Paths can be joined with /, as in Path("data") / "notes.txt", which works on every operating system.

Common mistakes

  • Opening with "w" when you meant "a", wiping the file.
  • Forgetting encoding="utf-8".
  • Using a relative path and running the script from a different folder. Relative paths are resolved from the current working directory, not from the script's location.

Summary

  • open(path, mode, encoding="utf-8") returns a file object; "r", "w", "a" read, overwrite and append.
  • with closes the file for you.
  • Iterate over a file to read it line by line.
  • pathlib.Path offers read_text() and write_text() one-liners.

Quiz: Reading and writing files

1. Which mode adds to the end of an existing file without erasing it?

"a" appends; "w" truncates the file first.

2. What is the main benefit of with open(...) as f:?

The context manager closes the file even if an exception occurs.

3. When you loop over a file object, what does each line end with?

Lines keep their line ending; use rstrip("\n") or strip() to remove it.

Official docs

Written under the pen name Ethan Cole with AI-assisted drafting. Every code example on this page is executed by our test suite before publishing. Found a mistake? Tell us.