To read a file line by line in Python, open it in a with block and loop over the file object: for line in f:. Each line keeps its trailing \n, so call line.rstrip("\n") when you need the bare text.
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.rstrip("\n"))
This reads one line at a time, so it works the same on a 1 KB file and a 50 GB log. The with block closes the file when the loop ends, even if an exception is raised inside it.
What each line actually contains
Here is a 4-line test file, where the last line has no trailing newline and line 2 is blank:
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(repr(line))
Output (Python 3.12):
'first line\n'
'\n'
'third line\n'
'last line no newline'
Three things to notice. Every line ends in \n except possibly the last one. A blank line is '\n', not an empty string. And on Windows you still see \n, not \r\n: in text mode Python translates \r\n and \r line endings to \n when reading (the default "universal newlines" behaviour of open()).
Strip the newline: rstrip("\n") vs strip()
| Call | Removes | Use when |
|---|---|---|
line.rstrip("\n") | Only trailing newlines | Leading or trailing spaces are meaningful |
line.rstrip() | All trailing whitespace, including \r and tabs | Most text and config files |
line.strip() | Whitespace at both ends | You want clean tokens, such as one word per line |
To skip blank lines, test the stripped value: if not line.strip(): continue.
Read a file line by line with line numbers
with open("notes.txt", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(number, line.rstrip("\n"))
Output:
1 first line
2
3 third line
4 last line no newline
start=1 makes the count match what an editor shows. This is the pattern to use when you report errors like "bad value on line 3".
readline(), readlines() and read().splitlines()
The file object offers other ways to get lines. They differ in how much memory they use and what the lines look like:
| Method | Returns | Newlines kept? | Memory |
|---|---|---|---|
for line in f | One line per iteration | Yes | One line at a time |
f.readline() | The next line, or '' at end of file | Yes | One line at a time |
f.readlines() / list(f) | List of all lines | Yes | Whole file |
f.read().splitlines() | List of all lines | No | Whole file, twice briefly |
Real output for the same test file:
>>> f.readlines()
['first line\n', '\n', 'third line\n', 'last line no newline']
>>> f.read().splitlines()
['first line', '', 'third line', 'last line no newline']
readlines() is fine for a config file of a few hundred lines. On a multi-gigabyte log it loads everything into RAM at once, which is exactly what reading line by line is meant to avoid.
readline() is useful when you need to read a header line before looping over the rest:
with open("data.csv", encoding="utf-8") as f:
header = f.readline().rstrip("\n").split(",")
for line in f: # continues from line 2
values = line.rstrip("\n").split(",")
For real CSV files, use the csv module instead of split(","), because quoted fields can contain commas.
Always set the encoding
If you leave out encoding, Python picks one for you. On Python 3.14 and earlier that is the locale encoding, which on a Windows machine set to English is usually cp1252. Python 3.15 changed the default to UTF-8 (PEP 686). Until every machine that runs your code is on 3.15 or later, pass the encoding explicitly.
Without it, a UTF-8 file read on Windows with Python 3.12 does one of two things. Some characters silently turn into mojibake: café comes back as café. Others fail outright:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2: character maps to <undefined>
That error came from a file containing a curly closing quote (”, bytes e2 80 9d in UTF-8). Opening it with encoding="utf-8" reads it correctly. If a file has a few bad bytes that you can afford to lose, add errors="replace" to substitute � instead of raising.
Read only the first N lines
itertools.islice stops after N lines without reading the rest of the file:
from itertools import islice
with open("big.log", encoding="utf-8") as f:
for line in islice(f, 10):
print(line, end="")
print(line, end="") avoids a double newline, since line already ends in one. To skip a header and read lines 2 to 11, use islice(f, 1, 11).
Count lines or search a large file
with open("big.log", encoding="utf-8") as f:
total = sum(1 for _ in f)
with open("big.log", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
if "ERROR" in line:
print(f"{number}: {line.rstrip()}")
Both run in constant memory. The second is a small grep -n; the same loop is a good base for parsing logs into structured records.
pathlib: read_text().splitlines() for small files
from pathlib import Path
lines = Path("notes.txt").read_text(encoding="utf-8").splitlines()
One line, no with block, and no newline characters. It reads the whole file at once, so keep it for files you know are small.
Reading JSON Lines files
A .jsonl file holds one JSON document per line, so you read it line by line and parse each line separately:
import json
with open("events.jsonl", encoding="utf-8") as f:
events = [json.loads(line) for line in f if line.strip()]
Calling json.load(f) on the whole file fails with JSONDecodeError: Extra data. The difference between the two functions is covered in Python json.load vs json.loads.
If it still fails
FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt': the path is relative to the current working directory, not to your script. Printos.getcwd(), or build the path fromPath(__file__).parent / "notes.txt".- The loop prints nothing the second time: a file object is an iterator. Once a loop has reached the end, a second loop gets no lines. Reopen the file or call
f.seek(0). - Binary files: for images, archives or executables, open with
"rb"and read fixed-size chunks withf.read(65536). Lines mean nothing in binary data, and text mode would try to decode it. - If the traceback is long and confusing, how to read a stack trace explains which line to look at first.
Frequently asked questions
- What is the fastest way to read a file line by line in Python?
- Loop over the file object: for line in f. The Python tutorial describes this as memory efficient, fast and simple, because the file is read in buffered chunks and only one line is held at a time. It is also the shortest code.
- How do I read a file line by line without the newline character?
- Call line.rstrip('\n') inside the loop, or line.rstrip() to also remove trailing spaces and \r. If you want a list of lines without newlines and the file is small, f.read().splitlines() does it in one call.
- How do I read a specific line number from a file?
- Use enumerate(f, start=1) and stop when the counter reaches the line you want, or use itertools.islice(f, n - 1, n) to jump to line n. Both still read the earlier lines, because a text file has no index of where each line starts.
- Why does Python say UnicodeDecodeError when reading a text file?
- The bytes in the file aren't valid in the encoding Python used to decode them. Before Python 3.15, Windows defaults to the locale encoding (often cp1252), so UTF-8 files can fail or turn into mojibake. Pass encoding='utf-8' to open() to fix it.