Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk2 min

How to Read a File Line by Line in Python

Read a Python text file sequentially with a context manager and direct file iteration, then choose readline(), list-based methods, or binary mode when appropriate.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Open the text file with with open(...), then loop over the file object: for line in file. This processes lines one at a time without first loading the whole file into memory.

Read a text file one line at a time

For ordinary sequential processing, iterate directly over the file object. Specify the file’s known encoding; UTF-8 is a common choice when it matches the file.

with open("path/to/file.txt", encoding="utf-8") as file:
    for line in file:
        process(line)

Replace "path/to/file.txt" with the file’s path and process(line) with the work you want to do for each line, such as checking it or extracting a value. The Python tutorial describes looping over a file object as memory efficient, fast, and simple. Iteration avoids collecting every line into a list first.

Choose the right reading method

Method What it does Use it when
for line in file Yields lines successively. You want to process a text file from beginning to end without collecting all its lines.
file.readline() Returns one line per call; returns an empty string at end of file. Your code needs to request each next line explicitly.
file.readlines() or list(file) Collects the file’s lines in a list. You need the lines together in memory.
file.read() without a size Reads the entire file into one string. You need the whole text at once and the file size is suitable for available memory.

For large inputs, prefer iteration or repeated readline() when you only need sequential processing. readlines(), list(file), and an unbounded read() materialize the content in memory. The Python tutorial’s file-object methods documents these options.

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

Handle newlines and blank lines

In text mode, Python normalizes platform-specific line endings. A line produced by iteration or readline() usually still ends with a newline character. If you print it unchanged, suppress print()’s additional newline:

with open("path/to/file.txt", encoding="utf-8") as file:
    for line in file:
        print(line, end="")

A final line does not have to end with a newline in the source file. Also distinguish a blank line from end of file: readline() returns a newline string for a blank line, while an empty string means there is no line left to read.

Use a context manager and an explicit encoding

The with statement closes the file when the block ends, including when an exception interrupts the block. It is a reliable default for file-reading code. Python’s default text encoding can vary by platform, so specify the encoding when it is known. Use encoding="utf-8" for a UTF-8 file; if the file uses another encoding, specify that encoding instead. See the official file I/O tutorial.

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

Read binary files as bytes

The examples above are for text. Text mode decodes file contents into strings and handles newlines. For binary formats such as images or executables, open the file in binary mode instead; binary reads return bytes and avoid text-mode newline conversion. Do not treat binary content as ordinary text.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
with open("path/to/file.bin", "rb") as file:
    for chunk in file:
        process_bytes(chunk)

In this binary example, iteration yields chunks separated by newline bytes, not decoded text lines. For a format-specific binary parser, follow that format’s structure rather than assuming newline-separated records.

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
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.