Sub topic 14
Reading and writing text files
This chapter assumes you can run a Python script and use try/except. It also assumes you know print(), f-strings, and the standard streams from earlier chapters. Here you will apply those skills to files on disk. You will open a file, write and read text, and avoid the mistakes that cause lost data or confusing output.
The open() function and the with block
open() asks the operating system for a connection to a file and returns a file object. In text mode, which is the default, that object reads and writes str values.
A file object holds an operating system resource, so it must be closed when you finish. Closing also flushes buffered output to disk. The with statement does this for you, even if an exception occurs inside the block.
with open("notes.txt", "w", encoding="utf-8") as f:
print("first line", file=f)
f.write("second line\n")
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.rstrip("\n"))The first block creates notes.txt. It writes one line with print() and one with write(). The second block opens the file for reading and prints each line.
Always pass encoding="utf-8" explicitly. If you leave it out, Python uses a platform-dependent default. A file written on one machine may then be read incorrectly on another. The next chapter covers encodings in detail.
Choosing a mode
The second argument to open() is the mode string. It controls what you can do and what happens to existing content.
| Mode | Meaning | If the file exists | If the file is missing |
|---|---|---|---|
| `"r"` (default) | Read only | Opens at the start | `FileNotFoundError` |
| `"w"` | Write only | Truncates it to empty | Creates it |
| `"a"` | Append only | Writes go to the end | Creates it |
| `"x"` | Exclusive create, write only | `FileExistsError` | Creates it |
| `"r+"` | Read and write | Opens at the start, no truncation | `FileNotFoundError` |
Add "t" for text mode (the default) or "b" for bytes. This chapter covers text mode only.
Writing: print() versus write()
Both methods put text into a file, but they behave differently.
f.write(s)writes exactly the strings. It adds no newline and accepts onlystr. It returns the number of characters written.print(..., file=f)converts each argument withstr(), joins them withsep, and appendsend, which is a newline by default.
with open("report.txt", "w", encoding="utf-8") as f:
f.write("Name,Score\n")
for name, score in [("Ada", 93.456), ("Linus", 88.0)]:
f.write(f"{name},{score:.1f}\n")
print("Total rows:", 2, file=f)f.write(42) raises TypeError because 42 is not a string. Either convert it yourself, as with f.write(str(42)), or let print() do it. For several values per line, use f-strings with write() or call print(). writelines() accepts an iterable of strings, but it also adds no newlines, so each string must already end with "\n".
Appending
Append mode is useful for logs and any file that grows over time.
import datetime
def log(message):
stamp = datetime.datetime.now().isoformat(timespec="seconds")
with open("app.log", "a", encoding="utf-8") as f:
print(f"{stamp} {message}", file=f)
log("started")
log("finished")Each call opens the file, adds one line at the end, and closes it. Running the script again adds more lines instead of replacing them.
Reading: three approaches
Which approach to use depends on the file size and what you need to do with the contents.
| Method | Returns | Use when |
|---|---|---|
| `f.read()` | One string with the whole file | The file is small and you want it as one text |
| `f.readlines()` | A list of lines, each keeping its `"\n"` | You need random access to lines and the file is small |
| `for line in f` | One line at a time | Most cases, including large files |
Iterating over the file object reads lazily, so memory use stays small even for a multi-gigabyte log. Each line still ends with "\n", except possibly the last. Strip it with line.rstrip("\n"), or use line.strip() to remove all surrounding whitespace.
longest = ""
count = 0
with open("notes.txt", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
text = line.rstrip("\n")
count = number
if len(text) > len(longest):
longest = text
print(f"{count} lines, longest: {longest!r}")Notice the !r in the f-string. If the longest line has trailing spaces or other hidden characters, repr() shows them.
f.read() and splitlines() together give a list of lines without the newline characters:
with open("notes.txt", encoding="utf-8") as f:
lines = f.read().splitlines()
print(lines)A file object is a one-way cursor
A file object keeps a position. Reading moves it forward, and it does not rewind on its own. This catches many people the first time.
with open("notes.txt", encoding="utf-8") as f:
first_pass = [line.rstrip("\n") for line in f]
second_pass = [line.rstrip("\n") for line in f]
print(first_pass)
print(second_pass)first_pass holds every line. second_pass is an empty list, because the cursor is already at the end. To read again, call f.seek(0) to return to the start, or open the file a second time.
Mixing styles on one file object is another source of confusion. Calling f.readline() works with iteration, but f.tell() can raise OSError after a for loop has begun reading, because Python buffers ahead. Choose one style per pass.
Handling missing files and bad paths
Opening a file is an operation that can fail. The common failures each have their own exception:
FileNotFoundError: the path does not exist, or a parent folder is missing when writing.PermissionError: you lack the right to read or write there.IsADirectoryError: the path names a folder.FileExistsError: you used mode"x"on an existing file.
All of these are subclasses of OSError, so catching OSError handles them as a group. Combine this with the retry pattern from the input-validation chapter:
import sys
while True:
path = input("File to read: ")
try:
with open(path, encoding="utf-8") as f:
content = f.read()
except FileNotFoundError:
print(f"{path!r} was not found, try again.", file=sys.stderr)
except OSError as err:
print(f"Cannot read {path!r}: {err}", file=sys.stderr)
break
else:
print(f"Read {len(content)} characters.")
breakError messages go to sys.stderr, so redirecting the normal output of the script to a file does not hide them.
Paths with pathlib
pathlib.Path builds paths without manual string joining and has shortcuts for small files.
from pathlib import Path
folder = Path("output")
folder.mkdir(exist_ok=True)
target = folder / "summary.txt"
target.write_text("Total: 3\n", encoding="utf-8")
print(target.read_text(encoding="utf-8"), end="")
print(target.exists())write_text() and read_text() open, process, and close the file in one call. They suit small files. For large files or line-by-line work, use with open(target, ...) or with target.open(...). Both accept a Path object.
Output reaches the disk later than you think
Python buffers writes. Text you have written may sit in memory until the buffer fills or the file is closed. Leaving the with block flushes it. If a program crashes or you read the file from another process while it is still open, you may see an incomplete file. Call f.flush() to push buffered text out without closing. For log files that others tail while the program runs, print(..., file=f, flush=True) does the same for one call.
Common mistakes
- Using
"w"when"a"was intended, which erases earlier data. - Forgetting the
"\n"withwrite(), which gives one long line. - Omitting
encoding, which produces different results across machines. - Reading a file twice from the same object without
seek(0). - Calling
read()on a very large file and running out of memory. - Opening a file with
"w"for writing, then trying to read from the same object. Use"r+", or open it again in"r"mode.
Exercise
A script runs open("data.txt", "w") to check whether a file has content, then reads it. Every run reports the file as empty, even though it had content before. What went wrong, and which change fixes it?
Show answer
Mode "w" truncates the file as soon as it is opened, so the original content is erased before the script reads anything. Open the file with mode "r" (the default) to read it, and add encoding="utf-8".
Exercise
Write a function copy_numbered(src, dst) that reads the text file src line by line and writes each line to dst with a line number in front, such as 1: first line. Use with blocks and an explicit encoding, and do not load the whole file into memory.
Show answer
def copy_numbered(src, dst):
with open(src, encoding="utf-8") as fin, open(dst, "w", encoding="utf-8") as fout:
for number, line in enumerate(fin, start=1):
print(f"{number}: {line.rstrip('\n')}", file=fout)
Note: on Python versions before 3.12, an f-string expression cannot contain a backslash, so compute text = line.rstrip("\n") first and use {text} in the f-string.