Explain it simply
Explain it simply
Working with a file is like borrowing a book from a library. open() is the borrowing step, and you say up front whether you want to read it (r), write it from scratch (w), or add pages at the end (a). When you are done you must give the book back; that is close().
A with statement is like a librarian who collects the book automatically. The moment the block ends, whether it finishes normally or leaves because of an error, the file is closed. That is why Python code opens files with with almost every time.
Problem → Why → Solution
The problem: file code that works on your machine only
The script below works on a Linux laptop. Send the notes.txt it creates to a teammate on Windows, read it there with the same encoding-less open(), and the é can turn into garbled characters or a UnicodeDecodeError. Worse, the division on line 3 crashes before close() runs, so the file stays open and the line written to it may never reach the disk.
f = open("notes.txt", "w") # no encoding: depends on the machine
f.write("Café menu: naan, mohinga\n")
total = 10 / 0 # crash: the next line never runs
f.close()
g = open("notes.txt") # may decode with a different encoding
print(g.read())Why does this happen?
Without an encoding argument, Python uses the operating system's default. That is usually UTF-8 on Linux and macOS, but on Windows it can be a legacy code page such as cp1252. Text like é written in one encoding and read in another breaks. And because close() is called by hand, it is easy to skip on the error path.
Core concept: path, mode, encoding and lifetime
Every time you open a file you make four decisions: which file (path), what to do with it (mode), how text becomes bytes (encoding), and how long it stays open (lifetime). open(path, mode, encoding=...) answers the first three, and a with block answers the fourth.
| Mode | If the file exists | If it does not exist |
|---|---|---|
| "r" (default) | Reads from the start | FileNotFoundError |
| "w" | Empties it at once (truncates), then writes | Creates it |
| "a" | Writes after the existing content | Creates it |
| "x" | FileExistsError | Creates it |
Adding "b" to the mode ("rb", "wb") handles the file as raw bytes instead of text, which is what you need for images, PDFs or zip files. Binary mode takes no encoding. Adding "+" ("r+") allows reading and writing at once, but you then have to track the file position yourself, so beginners should avoid it.
In text mode Python converts strings to bytes with the encoding and also handles newlines: on reading, \r\n becomes \n, so a file written on Windows still splits into the right lines elsewhere. Because the default encoding depends on the machine, the Python documentation itself recommends passing encoding explicitly.
Python collects written data in a buffer before it goes to the disk. close() flushes that buffer and releases the operating system's file handle. A with block calls close() even when an exception occurs, which prevents lost data and leaked handles. For the path itself, join parts with the / operator, as in pathlib.Path(folder) / "notes.txt", so you never have to choose between Windows backslashes and Linux slashes.
pathlib also offers shortcuts for small files. path.read_text(encoding="utf-8") opens, reads and closes in a single call, and path.write_text(text, encoding="utf-8") does the same for writing. They are ideal for config files of a few kilobytes. For anything that can grow, such as logs or exports, stay with open() and process the file line by line or in chunks so memory use stays flat.
- Build the path with Path()
- open() with a mode and an encoding
- Read or write inside the with block
- Block ends: the file closes itself
Never use the file object after its with block; by then it is closed.
General pattern
from pathlib import Path
path = Path(folder) / "file_name.txt"
with open(path, "mode", encoding="utf-8") as f: # mode: r, w, a or x
data = f.read() # or f.write(text), or: for line in f
# the file is closed here, even after an exception
with open(path, "rb") as f: # binary: no encoding
raw = f.read()Join the path with /, then do the work inside with open(...) as f:. Text mode takes an encoding; binary mode ("rb", "wb") does not. Where the indented block ends, the file is already closed.
Example: write, append, read back
This example works inside tempfile.TemporaryDirectory(), which creates a scratch folder and deletes it, files and all, when the block ends, so nothing is left in your project folder. It uses three modes in a row and checks f.closed to prove that with really closed the file.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "notes.txt"
with open(path, "w", encoding="utf-8") as f: # "w": create or overwrite
f.write("Hello, this is a new file.\n")
f.write("This is the second line.\n")
print(f"Created {path.name}, closed: {f.closed}")
with open(path, "a", encoding="utf-8") as f: # "a": add to the end
f.write("Appended line.\n")
with open(path, "r", encoding="utf-8") as f: # "r": read (the default)
for number, line in enumerate(f, start=1):
print(number, line.rstrip("\n"))
print(f"Exists inside the block: {path.exists()}")
print(f"Exists after cleanup: {path.exists()}")Code breakdown
- Line 5
path = Path(tmp) / "notes.txt"The / operator joins folder and file name with the right separator for the operating system. path.name is just "notes.txt", so the long temporary folder path never appears in the output.
- Lines 7-10
with open(path, "w", encoding="utf-8") as f: # "w": create or overwrite"w" creates the file because it does not exist yet. write() adds no newline on its own, so each string ends with \n. On line 10, outside the block, f.closed is already True.
- Lines 12-13
with open(path, "a", encoding="utf-8") as f: # "a": add to the end"a" leaves the two existing lines alone and writes after them. Using "w" here instead would wipe out the first two lines.
- Lines 15-17
for number, line in enumerate(f, start=1):Iterating a file object with a for loop yields one line at a time. Each line still ends in \n, which rstrip("\n") removes; without it, print() would add blank lines between them.
- Lines 19-21
print(f"Exists after cleanup: {path.exists()}")Inside the TemporaryDirectory block the file exists; once the block ends the whole folder is deleted, so the check prints False.
Created notes.txt, closed: True
1 Hello, this is a new file.
2 This is the second line.
3 Appended line.
Exists inside the block: True
Exists after cleanup: FalseKnow the file errors by name
The exceptions you meet in file code are distinct types: FileNotFoundError when the file is missing, PermissionError when you lack access, FileExistsError for mode "x" on an existing file, and UnicodeDecodeError when the encoding is wrong. The first three are subclasses of OSError. The code below shows what happens when a file written as latin-1 is read as UTF-8.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
try:
with open(folder / "missing.txt", encoding="utf-8") as f:
f.read()
except FileNotFoundError as err:
print(f"{type(err).__name__}: {Path(err.filename).name}")
legacy = folder / "legacy.txt"
legacy.write_bytes("café".encode("latin-1")) # bytes b'caf\xe9'
try:
legacy.read_text(encoding="utf-8")
except UnicodeDecodeError as err:
print(f"UnicodeDecodeError at byte {err.start}")
print(legacy.read_text(encoding="latin-1") == "café")In real projects
Where this shows up in real projects
Data pipelines, report generators and config loaders are all built on file handling. The usual shape is: read an input file as UTF-8 one line at a time, validate each line, and write an output file. Streaming instead of loading everything at once lets the same code process gigabyte-sized log files with very little memory.
Production code handles each error type differently. FileNotFoundError gets a message asking the user to check the path, PermissionError gets logged together with the account the program runs as, and UnicodeDecodeError means asking whoever supplied the data which encoding they exported. In tests, files are created in a temporary directory just like this lesson's example, so every test starts clean and cannot disturb another; pytest's tmp_path fixture does exactly that.
Common mistakes
Common mistakes
1. Opening with "w" when you meant to read
open(path, "w") empties the file the moment it opens, before you call write() even once. Use "r" (or no mode at all) to read, and "a" to add to the end.
2. Leaving out the encoding
open("data.txt") works on your machine and can fail with UnicodeDecodeError or garbled text on one with a different default encoding. Pass encoding="utf-8" on every text file.
3. Using the file after its with block
Calling f.read() after the with block raises ValueError: "I/O operation on closed file". Store what you need in a variable inside the block, then use that variable outside it.
4. Writing a Windows path in a plain string
open("C:\new\data.txt") does not open the file you think, because \n inside a plain string is a newline character. Use a raw string such as r"C:\new\data.txt", forward slashes, or better, Path("C:/new") / "data.txt".
Best practices
Best practices
- Carry paths around as Path objects rather than strings, all the way to the open() call.
- Run tests and experiments in tempfile or pytest's tmp_path so no stray files land in your project folder.
- Build relative paths from Path(__file__).parent instead of trusting the current working directory.
Mini challenge
Mini challenge: copy a file in upper case
Write copy_upper(), which reads a source file line by line and writes each line in upper case to a target file. Try it only inside a temporary directory.
- Open both files with with and encoding="utf-8"
- Process the source one line at a time, not with a single read()
- Return the number of lines copied
- Catch FileNotFoundError for a missing source and print a message
import tempfile
from pathlib import Path
def copy_upper(source: Path, target: Path) -> int:
"""Copy source to target in upper case and return the number of lines."""
# TODO: open source for reading and target for writing, both as utf-8
# TODO: loop over the source lines, write each one upper-cased, count them
...
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
# TODO: create input.txt with three short lines
# TODO: call copy_upper(), print the count and the new file's content
# TODO: call it with a missing source and print a friendly messageExpected: The program prints: Copied 3 lines APPLES BANANAS CHERRIES Source file not found, nothing copied
Show hint
You can put two context managers in one parenthesized with ( open(...) as src, open(...) as dst, ): (Python 3.10+). line.upper() leaves the \n alone, so you do not need to add one.
Show solution
import tempfile
from pathlib import Path
def copy_upper(source: Path, target: Path) -> int:
"""Copy source to target in upper case and return the number of lines."""
count = 0
with (
open(source, "r", encoding="utf-8") as src,
open(target, "w", encoding="utf-8") as dst,
):
for line in src:
dst.write(line.upper())
count += 1
return count
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
source = folder / "input.txt"
source.write_text("apples\nbananas\ncherries\n", encoding="utf-8")
lines = copy_upper(source, folder / "output.txt")
print(f"Copied {lines} lines")
print((folder / "output.txt").read_text(encoding="utf-8"), end="")
try:
copy_upper(folder / "nope.txt", folder / "nope_upper.txt")
except FileNotFoundError:
print("Source file not found, nothing copied")Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Opening a file means choosing a path, a mode, an encoding and a lifetime.
- "r" reads, "w" truncates then writes, "a" appends, "x" creates only if missing, "b" means bytes.
- with open(...) as f: closes the file even when an error occurs.
- Pass encoding="utf-8" on every text file and build paths with pathlib.Path and /.
Python Documentation — Reading and Writing Files — Python Software Foundation