r/pythontips • u/ClickOk5811 • 13h ago
Syntax Reading the last line of a file when it has no trailing newline
A common Python mistake is splitting file content by "\n" and assuming every line ends with a newline. If the last line does not, split("\n") still returns it as a final element, but code that iterates with readline() or relies on endswith("\n") can silently drop or mishandle it.
The fix is to use splitlines(), which splits on any line boundary and does not require a trailing newline:
with open("data.txt", "r", encoding="utf-8") as f:
lines = f.read().splitlines()
for line in lines:
print(line)If you need to preserve the line endings themselves, use splitlines(keepends=True):
with open("data.txt", "r", encoding="utf-8") as f:
lines = f.read().splitlines(keepends=True)
for line in lines:
print(line, end="")This works the same whether the file ends with \n, \r\n, or nothing at all.
One edge case: an empty file returns an empty list from splitlines(), which is usually what you want.
Question: Do you handle the no-trailing-newline case explicitly in your file-reading code, or do you assume inputs always end with a newline?