Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk3 min

How to Read the Last Line of a File in Python

Read a text file’s last line in Python without storing every line, with examples for empty files, newline handling and small-file alternatives.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a general text file, read it line by line and keep the most recently read line. This uses memory for only one line at a time, even though Python still reads the file from start to finish.

Read the last line without storing the whole file

Python file objects can be iterated one line at a time. Use a None sentinel so an empty file is distinguishable from a file whose final line is blank:

As an Amazon Associate I earn from qualifying purchases.

last_line = None
with open(path, encoding="utf-8") as f:
    for line in f:
        last_line = line

if last_line is not None:
    last_line = last_line.rstrip("rn")

Replace path with the file path and use the file’s actual encoding if it is not UTF-8. Specifying an encoding avoids relying on a platform-dependent default. The with block closes the file when it exits, including if an exception occurs. Python’s tutorial on input and output describes iterating over a file and its line-reading behavior; the built-in open() reference documents encoding and newline options.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep or remove the line ending

Iteration normally returns the line terminator along with the line. The final line may have no terminator if the file does not end with a newline. The rstrip("rn") call removes trailing carriage-return and newline characters, but leaves other whitespace intact. Omit it if the caller needs the line ending.

With default universal-newline handling, Python translates common input line endings such as CRLF and CR to n. If the original line-ending bytes matter, read in binary mode or configure newline handling deliberately, then decode with an approach appropriate to the file format.

Handle empty files and blank final lines

If the file is empty, the loop does not run and last_line remains None. A blank final line is still a line: before trimming, its value is a newline string. Checking last_line is not None preserves that distinction; checking only whether the value is truthy after stripping could lose it. Python’s file input tutorial also explains that readline() returns an empty string at end-of-file, unlike a blank line, which contains a line terminator.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose an approach for your file

Approach When it fits Tradeoff
Iterate and retain the last line General text files; the recommended default Reads the file sequentially, but does not keep all its lines in memory.
readlines(), then select the final item Small files where retaining all lines is acceptable Creates a list containing the file’s lines, so memory use grows with the file.
Scan backward from the end Specialized large-file optimization when the encoding and file format are known Requires careful binary handling of encoding and line boundaries; arbitrary end-relative offsets are not generally valid text-stream positions.

Use readlines() for small files

with open(path, encoding="utf-8") as f:
    lines = f.readlines()

last_line = lines[-1] if lines else None

This is compact and straightforward, but readlines() stores all lines in a list. Python documents this list-producing behavior in its file input tutorial and I/O reference.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why not seek backward in a text file?

A tempting shortcut is to seek a fixed number of bytes backward from the end, then read forward. That is not a safe general recipe for a text stream: Python restricts text-mode seeking to supported positions, and arbitrary offsets from the end are not generally valid. Even in binary mode, a correct reverse scan must account for the encoding, possible multibyte characters, CRLF boundaries, empty files and trailing newline runs. See the Python tutorial and I/O reference for text-stream seek semantics.

For ordinary text files, iteration is the simpler choice. A backward scan is appropriate only when its binary and encoding assumptions are explicit and the extra complexity is justified.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.