October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Print the Contents of a File in Python

Use a context manager and read() for a reasonably sized text file; iterate line by line for large files. Learn about UTF-8, pathlib, and binary data.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a text file that fits comfortably in memory, open it with a context manager and print the string returned by read():

with open("example.txt", encoding="utf-8") as f:
    print(f.read())

For a large file, iterate over its lines instead. The examples below show how to choose, avoid extra blank lines, and handle encoding and binary data.

As an Amazon Associate I earn from qualifying purchases.

Choose the right way to read the file

Situation Approach What to know
Small or moderate text file with open(path, encoding="utf-8") as f: print(f.read()) Simple, but reads the entire decoded file into memory.
Large text file Iterate over the file object and print each line with end="". Processes the file incrementally and avoids adding a second newline.
Path-oriented whole-file read Path(path).read_text(encoding="utf-8") Convenient, but still reads the whole file into memory.
Binary file, such as an image or executable Open in binary mode and process bytes. Text decoding and newline conversion are not suitable for arbitrary binary data.

Print a text file that fits in memory

Use open() with with so the file is closed when the block ends, even if an exception occurs:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
with open("example.txt", encoding="utf-8") as f:
    print(f.read())

With no size argument, f.read() returns the entire file as one string. This is straightforward for a reasonably sized file, but memory use grows with the file’s contents. Python’s tutorial recommends specifying UTF-8 unless you know the file requires another encoding: Python tutorial: Input and Output.

Print a large text file line by line

Iterating over the file avoids loading all its contents into memory at once:

with open("example.txt", encoding="utf-8") as f:
    for line in f:
        print(line, end="")

A line read from the file normally already includes its line ending. Since print() adds a newline by default, end="" prevents an extra newline after every line. This preserves the existing line breaks while processing incrementally. See the Python tutorial’s file iteration example.

Use pathlib for a concise whole-file read

If you prefer a path-oriented API, Path.read_text() reads and decodes a text file, returns its contents as a string, and closes the file when finished:

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

print(Path("example.txt").read_text(encoding="utf-8"))

This is convenient for a reasonably sized file, but like f.read(), it holds the full text in memory. The method is documented in the Python pathlib reference.

Set the encoding explicitly

Text mode converts the file’s bytes into a Python string, so the encoding must match the file. If you omit encoding, Python uses a platform-dependent default; the same code can therefore behave differently across environments. Specify the known encoding, using UTF-8 when appropriate. The behavior of open() and its encoding parameter is described in the built-in open() reference.

If you see a decoding error, check how the file was saved and pass that encoding explicitly rather than relying on the machine’s default. In text mode, Python also translates platform-specific line endings by default.

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

Handle binary files as bytes

Do not use a text-reading pattern to display arbitrary binary data such as a JPEG or executable. Text mode decodes bytes and may translate line endings, neither of which is appropriate for general binary content. Open binary data with a mode containing b, such as "rb", and process the resulting bytes according to the file format. See the open() documentation.

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

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
Windows Errors? Fix Them Before They SpreadFree repair scan
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.