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 getFileNotFoundError."w"writes, creating the file or erasing an existing one first."a"appends to the end, creating the file if needed.- Add
bfor 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.
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.withcloses the file for you.- Iterate over a file to read it line by line.
pathlib.Pathoffersread_text()andwrite_text()one-liners.
Quiz: Reading and writing files