Python course · Module 7: Files and errors · Lesson 32 of 63
Quick answer: To read a file in Python, open it in a with block and call read(): with open("shopping.txt", encoding="utf-8") as f: text = f.read(). To write, open it with mode "w" (replaces the file), "a" (adds to the end) or "x" (only creates a new file) and call write(). The with block closes the file for you, even after an error. Always pass encoding="utf-8", so your program reads and writes the same text on every computer and every Python version.
In this lesson you will learn:
- how to write and read a text file with
open()andwith - the file modes
"r","w","a"and"x" read(),readline(),readlines()and looping over lines;write()andwritelines()- why
encoding="utf-8"matters and how to fixUnicodeDecodeErrorandFileNotFoundError - how line endings work, with a small log-file example
Before you start: finish Lesson 31, pyproject.toml Explained: uv vs pip vs Poetry. You need for loops from Lesson 12 and string methods like split() and strip() from Lesson 20. All examples were run on Linux with Python 3.14.6 and gave the same output on Python 3.15.2, the newest release on python.org, except for one line that we point out.
Table of Contents
Write a text file with open() and with
open() gives you a file object, and its methods write or read the file. Let’s write a small shopping list:
with open("shopping.txt", "w", encoding="utf-8") as f:
f.write("Notebook\n")
count = f.write("Pen\n")
f.write("Backpack\n")
print("Characters written for Pen:", count)
print("File closed?", f.closed)
Characters written for Pen: 4
File closed? True
"shopping.txt"is the file name. A name without a folder means “in the current folder”, the folder you ran Python from."w"is the mode: open for writing. The file is created if it does not exist.encoding="utf-8"says how text is turned into bytes on the disk.write()does not add a line break, so we end each line with"\n". It returns the number of characters written:"Pen\n"is 4 characters.with ... as f:closes the file when the indented block ends.f.closedisTrueafterwards. The Python tutorial says the file “is properly closed after its suite finishes, even if an exception is raised at some point”. So always usewith.
Python read file: read() the whole file
Mode "r" (read) is the default, so you can leave it out:
with open("shopping.txt", encoding="utf-8") as f:
text = f.read()
more = f.read()
print(repr(text))
print(repr(more))
print(text, end="")
'Notebook\nPen\nBackpack\n'
''
Notebook
Pen
Backpack
read()returns the whole file as one string.repr()shows the hidden\ncharacters.- The second
read()returns''. The file object remembers its position, and after the firstread()it is at the end. The tutorial says that at the end of the filef.read()“will return an empty string”. end=""stopsprint()from adding one more line break, because the text already ends with\n.
Read line by line: readline(), readlines() and a for loop
with open("shopping.txt", encoding="utf-8") as f:
first = f.readline()
second = f.readline()
print(repr(first), repr(second))
with open("shopping.txt", encoding="utf-8") as f:
lines = f.readlines()
print(lines)
with open("shopping.txt", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(number, line.rstrip("\n"))
'Notebook\n' 'Pen\n'
['Notebook\n', 'Pen\n', 'Backpack\n']
1 Notebook
2 Pen
3 Backpack
readline()reads one line each time you call it, and keeps the\nat the end.readlines()returns a list of all lines, each with its\n.for line in freads one line per loop. The tutorial calls this “memory efficient, fast, and leads to simple code”, so it is the best choice for big files.enumerate()numbers the lines, andrstrip("\n")removes the line break.
What happens if you forget rstrip()?
with open("shopping.txt", encoding="utf-8") as f:
for line in f:
print(line)
Notebook
Pen
Backpack
Each line already ends with \n, and print() adds a second one. Use line.rstrip("\n"), line.strip() or print(line, end="").
File modes: r, w, a and x
These are the modes from the open() documentation you will use most:
| Mode | Meaning | If the file exists | If the file does not exist |
|---|---|---|---|
| “r” | read (the default) | read from the start | FileNotFoundError |
| “w” | write | everything in it is deleted first | it is created |
| “a” | append | new text goes at the end | it is created |
| “x” | exclusive create | FileExistsError | it is created |
Add "b" for binary mode (bytes instead of text), as in "rb". You saw "rb" in Lesson 31 with tomllib.
Append adds to the end and keeps the old lines:
with open("shopping.txt", "a", encoding="utf-8") as f:
f.write("Ruler\n")
with open("shopping.txt", encoding="utf-8") as f:
print(f.read(), end="")
Notebook
Pen
Backpack
Ruler
Write mode deletes the old content as soon as the file is opened:
with open("shopping.txt", "w", encoding="utf-8") as f:
f.write("Eraser\n")
with open("shopping.txt", encoding="utf-8") as f:
print(f.read(), end="")
Eraser
The four old lines are gone. Use "x" when you must never overwrite a file. It works the first time and fails the second time:
with open("report.txt", "x", encoding="utf-8") as f:
f.write("First report\n")
print("report.txt created")
with open("report.txt", "x", encoding="utf-8") as f:
f.write("Second report\n")
report.txt created
Traceback (most recent call last):
File "/home/learner/python-course/step7_exclusive.py", line 5, in <module>
with open("report.txt", "x", encoding="utf-8") as f:
~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileExistsError: [Errno 17] File exists: 'report.txt'
FileNotFoundError
Reading a file that does not exist, here because of a typo, stops the program:
with open("shoping.txt", encoding="utf-8") as f:
print(f.read())
Traceback (most recent call last):
File "/home/learner/python-course/err1_file_not_found.py", line 1, in <module>
with open("shoping.txt", encoding="utf-8") as f:
~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'shoping.txt'
Check the spelling and the folder. A file name without a folder is looked up in the current folder, so the same script can fail when run from another folder. Lesson 35 shows how to catch errors like this with try and except.
write() and writelines()
writelines() writes every string from a list (or any iterable). Like write(), it adds no line breaks:
items = ["Notebook", "Pen", "Backpack"]
with open("shopping.txt", "w", encoding="utf-8") as f:
f.writelines(items)
with open("shopping.txt", encoding="utf-8") as f:
print(repr(f.read()))
with open("shopping.txt", "w", encoding="utf-8") as f:
f.writelines(item + "\n" for item in items)
with open("shopping.txt", encoding="utf-8") as f:
print(repr(f.read()))
'NotebookPenBackpack'
'Notebook\nPen\nBackpack\n'
The first file is one long line. The fix adds "\n" to each item with a generator expression, the comprehension style from Lesson 21.
Always pass encoding=”utf-8″
A file stores bytes. The encoding is the rule that turns text into bytes and back. UTF-8 can store every language, from “é” to Urdu, so it is the usual choice.
What happens without encoding=? For Python 3.14, the 3.14 docs for open() say “the encoding used is platform-dependent”: Python asks the operating system (locale.getencoding()). PEP 686 says this “mostly affects Windows users”. Python 3.15 changed the default: its What’s New page says “Python now uses UTF-8 as the default encoding, independent of the system’s environment”. It does this by turning on UTF-8 mode. The same page still says to “ensure that an explicit encoding argument is always provided”, because your code may run on older Pythons.
This script shows the setting and what a wrong encoding does:
import locale
import sys
print("Python", sys.version.split()[0])
print("UTF-8 mode:", sys.flags.utf8_mode)
print("Locale encoding:", locale.getencoding())
with open("menu.txt", "w", encoding="utf-8") as f:
f.write("Crème brûlée: 450\n")
with open("menu.txt", encoding="utf-8") as f:
print(f.read(), end="")
with open("menu.txt", encoding="latin-1") as f:
print(f.read(), end="")
Python 3.14.6:
Python 3.14.6
UTF-8 mode: 0
Locale encoding: UTF-8
Crème brûlée: 450
Crème brûlée: 450
Python 3.15.2:
Python 3.15.2
UTF-8 mode: 1
Locale encoding: UTF-8
Crème brûlée: 450
Crème brûlée: 450
- UTF-8 mode is on (
1) in 3.15 and off (0) in our 3.14 run. WithPYTHONUTF8=0, Python 3.15.2 printed0again; the What’s New page names this as the way to keep the old behaviour. - On 3.14 you may see
1too: Python 3.14 turns UTF-8 mode on when the locale isCorPOSIX(3.14 docs), and with no locale set, our 3.14.6 printed1. - We used a UTF-8 locale (
LANG=C.UTF-8), so the default is UTF-8 in both versions. With another locale encoding, Python 3.14 would read and write differently. - Reading UTF-8 bytes as
latin-1gives no error, just wrong text:Crème.
To find every open() that has no encoding, run Python with -X warn_default_encoding. The io docs say it will “emit an EncodingWarning when the default encoding is used”:
with open("menu.txt") as f:
print(f.read(), end="")
$ python3 -X warn_default_encoding step10_encoding_warning.py
/home/learner/python-course/step10_encoding_warning.py:1: EncodingWarning: 'encoding' argument not specified
with open("menu.txt") as f:
Crème brûlée: 450
UnicodeDecodeError
The opposite problem: the file was saved in another encoding, and you read it as UTF-8. Here we save “Café” as latin-1 on purpose:
with open("cafe_latin1.txt", "w", encoding="latin-1") as f:
f.write("Café\n")
with open("cafe_latin1.txt", encoding="utf-8") as f:
print(f.read())
Traceback (most recent call last):
File "/home/learner/python-course/err2_unicode_decode.py", line 5, in <module>
print(f.read())
~~~~~~^^
File "<frozen codecs>", line 325, in decode
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte

In latin-1, “é” is the single byte 0xe9. In UTF-8, “é” is two bytes, 0xc3 0xa9, so the UTF-8 reader finds a byte that does not fit at position 3 (counting from 0) and stops. Two fixes:
with open("cafe_latin1.txt", encoding="latin-1") as f:
print(f.read(), end="")
with open("cafe_latin1.txt", encoding="utf-8", errors="replace") as f:
print(f.read(), end="")
Café
Caf�
The best fix is the encoding the file was really saved in. errors="replace" only hides the problem by putting � where a byte did not fit.
Line endings and the newline parameter
Linux and macOS end lines with \n. Windows uses two characters, \r\n. Python hides this difference when it reads text:
import os
with open("windows_lines.txt", "wb") as f:
f.write(b"Notebook\r\nPen\r\n")
with open("windows_lines.txt", encoding="utf-8") as f:
print(f.readlines())
with open("windows_lines.txt", encoding="utf-8", newline="") as f:
print(f.readlines())
print(repr(os.linesep))
['Notebook\n', 'Pen\n']
['Notebook\r\n', 'Pen\r\n']
'\n'
- We wrote real Windows line endings with binary mode
"wb"and bytes (b"..."). - Normal text mode turned
\r\ninto\n, so your code only needs to handle\n. newline=""keeps the line endings exactly as they are in the file. You will meet it again with CSV files in Lesson 34.- When writing, the open() docs say each
\nbecomes the “system default line separator,os.linesep“. The os docs say that is'\n'on Linux and'\r\n'on Windows.
Example: a small log file
This script writes a log, appends a line, counts the levels and saves the errors in a second file:
log_lines = [
"2026-11-08 09:00:01 INFO Server started\n",
"2026-11-08 09:05:12 WARNING Disk 85% full\n",
"2026-11-08 09:07:40 ERROR Payment failed for order 1042\n",
"2026-11-08 09:15:03 INFO User Sara logged in\n",
"2026-11-08 09:20:55 ERROR Email server not reachable\n",
]
with open("app.log", "w", encoding="utf-8") as log:
log.writelines(log_lines)
with open("app.log", "a", encoding="utf-8") as log:
log.write("2026-11-08 09:30:00 INFO Backup finished\n")
counts = {}
errors = []
with open("app.log", encoding="utf-8") as log:
for line in log:
date, time, level, message = line.rstrip("\n").split(" ", 3)
counts[level] = counts.get(level, 0) + 1
if level == "ERROR":
errors.append(f"{time} {message}\n")
with open("errors.txt", "w", encoding="utf-8") as out:
out.writelines(errors)
print(counts)
with open("errors.txt", encoding="utf-8") as f:
print(f.read(), end="")
{'INFO': 3, 'WARNING': 1, 'ERROR': 2}
09:07:40 Payment failed for order 1042
09:20:55 Email server not reachable
"w"creates the log, then"a"adds the sixth line without deleting the first five.split(" ", 3)splits at the first three spaces only, so the message keeps its spaces.- The dictionary
countsusesget(level, 0) + 1to count each level.
pathlib can do a whole read in one line. Lesson 33 covers it; here is a first look:
from pathlib import Path
print(Path("errors.txt").read_text(encoding="utf-8"), end="")
09:07:40 Payment failed for order 1042
09:20:55 Email server not reachable
Try it yourself
Exercise 1: A to-do file
Write the tasks "Buy milk", "Finish Lesson 32" and "Call Ali" to todo.txt, one per line, using a for loop. Then read the file and print the tasks numbered 1., 2., 3..
Exercise 2: Count lines and words
Count the lines and the words in app.log from the log example. Read it line by line and use split().
Exercise 3: A diary function
Write a function add_note(text) that adds one line to diary.txt without deleting older notes. Call it twice and print the file.
Solutions
Solution 1
tasks = ["Buy milk", "Finish Lesson 32", "Call Ali"]
with open("todo.txt", "w", encoding="utf-8") as f:
for task in tasks:
f.write(task + "\n")
with open("todo.txt", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(f"{number}. {line.strip()}")
1. Buy milk
2. Finish Lesson 32
3. Call Ali
write() needs the "\n", and strip() removes it again when printing.
Solution 2
line_count = 0
word_count = 0
with open("app.log", encoding="utf-8") as f:
for line in f:
line_count += 1
word_count += len(line.split())
print("Lines:", line_count)
print("Words:", word_count)
Lines: 6
Words: 38
split() with no argument splits at any whitespace, including the final \n.
Solution 3
def add_note(text):
with open("diary.txt", "a", encoding="utf-8") as f:
f.write(text + "\n")
add_note("Learned open() today")
add_note("Wrote my first log file")
with open("diary.txt", encoding="utf-8") as f:
print(f.read(), end="")
Learned open() today
Wrote my first log file
Mode "a" keeps old notes; with "w", only the last note would be left.
Common mistakes
- Using
"w"when you meant"a"."w"empties the file the moment it opens, as theEraserexample showed. - Leaving out
encoding=. It may work on your computer and break on another one or on an older Python. Run with-X warn_default_encodingto find every suchopen(). - Using the file after the
withblock. The file is closed, sof.read()fails withValueError: I/O operation on closed file. - Writing to a file opened for reading.
open("shopping.txt", encoding="utf-8")is mode"r", sof.write()fails withio.UnsupportedOperation: not writable. - Forgetting
"\n".write()andwritelines()never add line breaks, andprint(line)adds an extra one.
Frequently asked questions
How do I read a file line by line in Python?
Use a for loop over the file object inside a with block: for line in f:. Each line ends with \n, so use line.rstrip("\n") or line.strip() before printing. This reads one line at a time, so it also works for very large files.
What is the difference between “w” and “a” in Python?
Both open a file for writing and create it if it is missing. "w" deletes everything already in the file first, while "a" keeps it and adds your text at the end. Use "a" for logs and notes, and "w" when you want a fresh file.
How do I fix UnicodeDecodeError when reading a file?
The file was saved in a different encoding from the one you used to read it. Find out how it was saved and pass that encoding, for example encoding="latin-1". If you only need to see most of the text, errors="replace" puts � where bytes do not fit.
Summary
- Open files with
with open(name, mode, encoding="utf-8") as f:; the file is closed when the block ends, even after an error. "r"reads (default),"w"replaces the file,"a"adds to the end and"x"creates a new file only.read()returns the whole text,readline()one line,readlines()a list, andfor line in freads line by line.write()andwritelines()add no"\n"; Python turns\r\ninto\nwhen reading text.- Always pass
encoding="utf-8": Python 3.15 uses UTF-8 by default, but older versions usually use the system’s locale encoding.
Next lesson
Next: Lesson 33, Python pathlib: Work with File Paths the Modern Way.
Sources
- Built-in Functions: open() (Python 3 docs)
- open() in the Python 3.14 docs (platform-dependent default encoding)
- Reading and Writing Files (Python tutorial)
- What’s New in Python 3.15: UTF-8 as the default encoding
- PEP 686: Make UTF-8 mode default
- io: Text encoding and opt-in EncodingWarning (Python docs)
- Python UTF-8 Mode (Python 3.14 os docs)
- os.linesep (Python docs)
- Python downloads page (python.org)





