Sub topic 14
Reading and Writing Text Files
This chapter assumes you know basic Python syntax, str and int, if and while, and try/except. You have already used print() for output and input() for input. Files work the same way, but the data lives on disk and persists after your program ends.
Opening a file with a with block
The built-in open() function returns a file object. A file object holds an operating-system resource, so you must close it when you are done. If you forget, buffered data may never reach the disk.
The with statement solves this. It closes the file when the block ends, even if an exception occurs.
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"))Running this creates notes.txt and then prints:
first line
second lineChoosing a mode
The second argument to open() is the mode. The default is "r" (read text).
| Mode | Meaning | If the file exists | If the file is missing |
|---|---|---|---|
| `"r"` | Read | Reads from the start | Raises `FileNotFoundError` |
| `"w"` | Write | Erases the contents first | Creates it |
| `"a"` | Append | Adds to the end | Creates it |
| `"x"` | Create only | Raises `FileExistsError` | Creates it |
Writing: write() versus print()
Both calls write text to the file, but they differ in one detail.
f.write(text)writes exactly the string you give it. It does not add a newline, and it accepts only strings.print(..., file=f)converts its arguments withstr(), joins them withsep, and addsend, which is a newline by default.
Because print() also accepts sep and end, it is often the more convenient choice for line-oriented output.
Reading: three common patterns
The right pattern depends on the size of the file and what you need.
f.read()returns the whole file as one string. Use it for small files.f.readlines()returns a list of lines, each still ending in"\n".- Iterating with
for line in fyields one line at a time. It does not load the whole file, so it works for very large files.
Each line you read keeps its trailing newline. Call line.rstrip("\n") before printing, or print() will add a second one and leave blank lines between your output.
total = 0
with open("numbers.txt", "w", encoding="utf-8") as f:
for n in (10, 20, 30):
print(n, file=f)
with open("numbers.txt", encoding="utf-8") as f:
for line in f:
total += int(line)
print(f"Sum: {total}")This prints Sum: 60. Here int(line) works despite the newline, because int() ignores surrounding whitespace. This is the same type conversion you used with input().
How the pieces fit together
Common errors
FileNotFoundError: the path is wrong, or the program runs from a different working directory than you expect. Relative paths resolve against the current working directory, not the script's location.- Lost data after
"w": you reopened an existing file for writing. Switch to"a"if you meant to add. - Blank lines in output: you printed lines that still ended in
"\n". Strip the newline first. TypeErrorfromwrite(): it accepts only strings. Convert withstr(value)or an f-string, or useprint().- Garbled non-ASCII text: you omitted
encoding. Always passencoding="utf-8"explicitly, because the default depends on the operating system and can differ between machines.
Exercise
A script opens "log.txt" with mode "w" every time it runs, and the log only ever shows the most recent run. What one-character change keeps the history of earlier runs, and why does it work?
Show answer
Change "w" to "a". Mode "w" truncates the file when it is opened, which discards earlier content. Mode "a" appends, so new output is added to the end of the existing file.
Exercise
This code prints a blank line after every line of the file. Fix it. with open("data.txt", encoding="utf-8") as f: followed by for line in f: print(line)
Show answer
Each line keeps its trailing "\n", and print() adds another. Use print(line.rstrip("\n")) or print(line, end="").