Python Reading Text Files
What you will learn
- Opening a file with
open()andwith - Why to always give
encoding="utf-8" read(),readline(),readlines()and looping over a file- Removing the newline at the end of each line
- Position in a file:
tellandseek - Handling a missing file
1. Programs and files
Variables vanish when a program ends. Files keep data on disk between runs: notes, logs, settings, tables. A text file holds characters organised in lines. The first step in using one is to open it.
To make the examples repeatable, first create a small file fruits.txt (writing is covered in lesson 15.2):
with open("fruits.txt", "w", encoding="utf-8") as f:
f.write("apple\nbanana\ncherry\n")
The file now holds three lines. The \n is the newline character that ends each line.
2. open() with with
with open("fruits.txt", encoding="utf-8") as f:
data = f.read()
print(repr(data))
print(type(data), len(data))
'apple\nbanana\ncherry\n'
<class 'str'> 20
Pieces of the call:
| Part | Meaning |
|---|---|
"fruits.txt" |
the file's path: here in the current folder (lesson 15.4 covers paths properly) |
encoding="utf-8" |
how the bytes in the file are turned into characters |
| mode (second argument, omitted here) | "r" for reading is the default |
with ... as f |
closes the file automatically when the block ends (lesson 14.6) |
f |
the file object, used to read |
f.read() returns the whole content as one string, including the \n characters.
Why encoding="utf-8"?
A file stores bytes; the encoding says which characters they mean. If you leave encoding out, Python uses your computer's default, which differs between systems. On the Windows computer used to check these lessons the default was cp1252, not UTF-8, so a file containing café or Bengali letters could be read wrongly or fail. UTF-8 is the common standard that handles all languages, so always write encoding="utf-8" for text files. Reading a UTF-8 file with the wrong encoding fails like this:
with open("uni.txt", encoding="ascii") as f:
f.read()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: ordinal not in range(128)
(uni.txt here held the text café ঢাকা.)
Quick check: what does `with` do when the block ends?
It closes the file, even if an error happened inside the block.
3. Ways to read
Take the same three-line file. Python keeps a position in the file, and each read continues where the last one stopped.
read(): everything at once
with open("fruits.txt", encoding="utf-8") as f:
print(f.read())
print(repr(f.read())) # position is now at the end
apple
banana
cherry
''
The second read() returns an empty string: nothing is left. An empty string is how Python says "end of file". f.read(5) reads only 5 characters.
readline(): one line at a time
with open("fruits.txt", encoding="utf-8") as f:
print(repr(f.readline()))
print(repr(f.readline()))
print(repr(f.readlines()))
print(repr(f.readline()))
'apple\n'
'banana\n'
['cherry\n']
''
readline()returns the next line with its\n(the last line of a file may lack one).readlines()returns all remaining lines as a list.- At the end,
readline()returns''.
Looping: the best way
A file object is iterable (lesson 12.4): a for loop gives one line at a time, without loading the whole file into memory:
with open("fruits.txt", encoding="utf-8") as f:
for line in f:
print(repr(line))
'apple\n'
'banana\n'
'cherry\n'
This is the standard way to read a file. It works for a file of any size, even bigger than your memory, because only one line is held at a time.
| Method | Returns | Use when |
|---|---|---|
f.read() |
one string | the file is small and you want it all |
f.readline() |
the next line | you need to read step by step |
f.readlines() |
a list of lines | you want a list and the file is small |
for line in f |
one line per pass | most cases, including large files |
4. Removing the newline
Each line ends in \n, which shows up as a blank line when printed, and sticks to values. Remove it with strip() or rstrip("\n") (lesson 4.3), or read everything and split:
with open("fruits.txt", encoding="utf-8") as f:
lines = [ln.rstrip("\n") for ln in f]
print(lines)
with open("fruits.txt", encoding="utf-8") as f:
print(f.read().splitlines())
['apple', 'banana', 'cherry']
['apple', 'banana', 'cherry']
strip()removes spaces and newlines at both ends;rstrip("\n")removes only the newline at the right.splitlines()splits a string at line breaks and drops them.print(line, end="")prints a line without adding another newline.
enumerate (lesson 6.6) adds line numbers:
with open("fruits.txt", encoding="utf-8") as f:
for n, line in enumerate(f, start=1):
print(n, line.strip().upper())
1 APPLE
2 BANANA
3 CHERRY
5. Newlines on different systems
Windows ends lines with two characters (\r\n), while Linux and macOS use one (\n). In text mode Python hides the difference: when reading, any line ending becomes \n, and when writing, \n becomes the system's own. On the Windows computer used here, the 20-character text above took 23 bytes on disk, and reading in binary mode ("rb", lesson 15.8) showed it:
with open("fruits.txt", "rb") as f:
print(f.read(7))
b'apple\r\n'
On a system that uses \n, you would see b'apple\n'. In your own programs you rarely need to care, which is the point of text mode.
6. Position: tell and seek
The file object remembers a position, which you can inspect and move:
with open("fruits.txt", encoding="utf-8") as f:
print(f.read(5), f.tell())
print(repr(f.read(3)))
f.seek(0)
print(f.read(5))
apple 5
'\nba'
apple
f.tell()gives the current position.f.seek(0)goes back to the start, so you can read the file again without reopening it.
(For text files, seek should be used with positions returned by tell or with 0.)
7. A missing file
If the file does not exist, open() raises FileNotFoundError (lesson 14.2):
try:
open("missing.txt")
except FileNotFoundError as e:
print(e)
[Errno 2] No such file or directory: 'missing.txt'
Handle it with try and except and a friendly message. Three common reasons: a typo in the name, the file is in a different folder from where the program runs, or it has not been created yet. Using a closed file also fails:
f = open("fruits.txt")
f.close()
f.read()
ValueError: I/O operation on closed file.
That is why with is best: you cannot forget to close, and you cannot use the file after the block.
Worked example: analysing a log file
A log has lines like 2026-03-01 09:15 INFO server started. Count how many lines have each level, skip blank lines, and show the line number and text of every error. The file is created first so the example can be repeated.
sample = """2026-03-01 09:15 INFO server started
2026-03-01 09:17 WARN disk 85% full
2026-03-01 09:20 ERROR cannot reach database
2026-03-01 09:21 INFO retrying
2026-03-01 09:22 ERROR cannot reach database
"""
with open("app.log", "w", encoding="utf-8") as f:
f.write(sample)
counts = {}
errors = []
with open("app.log", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
date, time, level, *words = line.split()
counts[level] = counts.get(level, 0) + 1
if level == "ERROR":
errors.append((number, " ".join(words)))
print(counts)
for number, message in errors:
print(f"line {number}: {message}")
{'INFO': 2, 'WARN': 1, 'ERROR': 2}
line 4: cannot reach database
line 6: cannot reach database
| Step | Idea |
|---|---|
for number, line in enumerate(f, start=1) |
a loop over the file with real line numbers |
line.strip() and if not line: continue |
removes the newline and skips the blank line 3 |
date, time, level, *words = line.split() |
unpacking with a starred name (lesson 8.3) |
counts.get(level, 0) + 1 |
counting with a dictionary (lesson 9.3) |
| a list of tuples for errors | collects what is needed for the report |
The log content is made up. Notice that the file is read once, line by line: the same code would work on a log of millions of lines.
Common mistakes
- Forgetting
encoding="utf-8", so the result depends on the computer. - Not using
with, and forgettingclose(). - Expecting
read()twice to give the data twice (the second returns''; useseek(0)or reopen). - Leaving
\non values, such as comparing"apple\n"with"apple". - Using
readlines()on a huge file (it loads everything; loop instead). - Running the program from a different folder than the file's, then getting
FileNotFoundError. - Using the file after the
withblock.
Key takeaways
- Use
with open(name, encoding="utf-8") as f:to read text safely. f.read()returns everything,readline()one line,readlines()a list; aforloop over the file is best for most work and for large files.- Lines keep their
\n: remove it withstrip(),rstrip("\n")orsplitlines(). - Reading continues from the current position;
seek(0)rewinds. An empty string means end of file. - A missing file raises
FileNotFoundError.
Practice
1. Why write encoding="utf-8" when opening a text file?
Show answer
Without it Python uses the computer's default, which differs between systems and may mis-read non-English characters. UTF-8 is the common standard.
2. Which is better for a very large file: f.readlines() or for line in f?
Show answer
for line in f: it holds one line at a time, while readlines() loads the whole file into memory.
3. What does f.read() return the second time you call it on the same open file?
Show answer
An empty string '', because the position is already at the end.
4. Write code that counts the lines in fruits.txt.
Show answer
with open("fruits.txt", encoding="utf-8") as f:
count = sum(1 for line in f)
print(count)
5. How can you read the file a second time without closing and reopening it?
Show answer
Call f.seek(0) to go back to the start.
6. What exception does open("nofile.txt") raise?
Show answer
FileNotFoundError.