Python Programming · Foundations

Reading Files

Want it in plain words first? Jump to Eli explains — the same idea, no jargon.
On this page 9 sections
  1. In 30 seconds
  2. Why this matters
  3. The college version
  4. Eli explains
  5. Worked example
  6. Key takeaway
  7. Quick check
  8. Study tools
  9. Sources & references

In 30 seconds

To read a text file in Python, open it with with open(path, encoding="utf-8") as file: and then ask the for content. read() gets the remaining text at once; readline() gets one line; and for line in file processes lines one at a time. The with block closes the file after its indented suite finishes.

Why this matters

Programs often begin with information stored outside the program: a class roster, a log, a configuration file, or notes saved as text. Reading that information carefully is a foundation for later analysis and automation. The method matters as much as the result: an explicit text makes assumptions visible, and processing a large file line by line can avoid holding all of it in memory. These habits transfer to data work, command-line tools, and debugging.

The college version

Opening a text stream safely

A file is data stored outside the running program. Python's built-in open() creates a file object that gives code a way to interact with that data. For an ordinary text file, a focused reading pattern is with open("names.txt", encoding="utf-8") as file: then enter an indented block. The with statement makes the file object a : when the block finishes, Python closes the file, even if the block exits because of an exception. Closing is not a decorative cleanup step. It ends the program's use of that resource and helps prevent later code from accidentally relying on an open handle. This lesson concentrates on reading; Writing Files covers changing file contents, and Exceptions covers how programs deliberately respond when a file cannot be opened.

Text is not raw bytes with a universal meaning. An encoding specifies how stored bytes represent characters. Python documentation notes that a default encoding can depend on the locale, so code that expects UTF-8 text should say encoding="utf-8" rather than silently depend on the machine's default. That is especially useful when a file contains names, accented characters, or symbols and the same code runs on different systems. In normal text reading, Python also translates common platform line endings into \n; code can therefore treat a line ending consistently without guessing which operating system created the file.

Three ways to obtain text

The method should fit the next operation. file.read() obtains the remaining contents as one string. It is convenient when a file is known to be small and the program truly needs the whole text at once—for example, checking whether one short configuration note contains a phrase. Calling it again at the end of the file returns an empty string because there is no remaining content.

file.readline() obtains one line at a time. Usually its returned string retains the trailing character. An empty string means , whereas a blank line is normally "\n"; that distinction lets a loop tell an empty line apart from no more lines. A program using readline() directly must manage that repeated step itself.

For many text-processing tasks, the clearest form is direct : for line in file:. A file object is iterable, so the loop requests successive lines without building a list of all lines first. The Python tutorial describes this as memory efficient and simple. It does not make a file magically small, but it means the program can process one line, discard or summarize it, and move to the next. If code needs to compare every line later, collecting lines may be appropriate; otherwise, iteration communicates that each line is handled as it arrives.

Position, transformations, and deliberate output

A file object has a current position. Reading advances that position, so read() followed by a loop over the same object will usually leave the loop with nothing to process. Choose one reading plan or reopen the file for a separate pass. Within a loop, line includes its newline when one was present in the source. line.rstrip("\n") is a deliberate way to remove that line ending while leaving other leading and trailing spaces alone. Plain strip() is broader and may remove meaningful spaces, so it should not be used automatically.

Consider a short attendee list with a deliberately blank line. Iteration can count nonblank names while preserving the distinction between a blank record and the end of the file. The program's output depends on three small choices: the context manager establishes the resource lifetime, encoding="utf-8" states how to decode text, and the loop reads one line at a time. This is a useful model for later data-processing code: make resource handling and transformations visible, and do not infer facts from data that have not been read.

Eli, the EliExplains learning guide

Eli explains

The same idea, in plain words

Explain it like I’m 10

A text file is like a notebook that lives outside your program. open lets the program look at it. The with block is a promise: use the notebook for this small job, then put it away when the job is over. Inside the block, read() means “show me all the remaining pages,” while a for loop means “show me one line, then the next.” A file remembers how far you have read, so the next request begins after the text already received.

Picture it like this

Imagine reading a long attendance sheet through a checkout scanner. Reading all at once is dumping the whole sheet onto a table. Iterating is scanning one name at a time and updating a count. If a line is blank, the scanner can notice that separately instead of pretending it is a name.

Where the picture stops working

A computer file is not paper: it has an encoding, a current read position, and can be much larger than a physical sheet. The scanner picture explains the choice of one-at-a-time processing, not every file behavior.

Worked example

Assume attendees.txt contains three lines: Ada, a blank line, and Lin. This program counts names without treating the blank line as a name:

name_count = 0

with open("attendees.txt", encoding="utf-8") as file:
    for line in file:
        name = line.rstrip("\n")
        if name != "":
            name_count += 1

print(name_count)

It prints 2. The loop receives "Ada\n", "\n", and "Lin\n"; rstrip("\n") changes them to Ada, an empty string, and Lin. The if skips only the blank line. The with block closes the file when its indented suite ends, before the outside print runs.

Key takeaway

Use with open(path, encoding="utf-8") for expected UTF-8 text, then choose read(), readline(), or direct iteration based on how much content the next step needs. Treat each choice as part of the program's data-handling design.

Quick check

3 questions here, of 5 in this lesson’s practice set. Answers stay hidden until you check.

Question 1 of 3foundational

What does with open("notes.txt", encoding="utf-8") as file: help ensure after its indented block finishes?

Choose an answer, then check it.
Question 2 of 3intermediate

Which operation is usually the clearest choice when a program must process a large text file one line at a time?

Choose an answer, then check it.
Question 3 of 3intermediate

For a text file expected to be UTF-8, why is encoding="utf-8" useful?

Choose an answer, then check it.
Practice all 5

Keep learning

Ready to build on this? Continue to the next lesson.

Practice this lesson
Study tools & related lessonsYou’ll learn to · Common mistakes · Easily confused · Key vocabulary · Related

You’ll learn to

  • Define a Python text file object and a context manager.
  • Distinguish read(), readline(), and direct line iteration.
  • Explain why with open(...) is a reliable reading pattern.
  • Apply an explicit UTF-8 encoding in a text-reading example.
  • Analyze when line-by-line processing is more appropriate than reading all text at once.

Common mistakes

  • Opening expected UTF-8 text without stating the encoding.

    Use encoding="utf-8" when UTF-8 is the intended format rather than relying on a locale-dependent default.

  • Using read() and then expecting a loop over the same file object to start at the beginning.

    Reading advances the current position; choose one pass or reopen the file for another pass.

  • Treating readline() == "" as a blank line.

    An empty string signals end of file; a blank line is normally represented by "\n".

  • Using strip() when only the line ending should disappear.

    Use rstrip("\n") to preserve other spaces unless removing them is intentional.

Easily confused

`read()` vs. `for line in file`

read() returns all remaining text as one string; direct iteration yields successive lines for processing.

empty string from `readline()` vs. a blank line

The empty string marks end of file; a blank text line normally contains a newline character.

implicit default encoding vs. `encoding="utf-8"`

The default can be locale-specific; the explicit argument documents and enforces the intended UTF-8 decoding.

Key vocabulary

file object
An object returned by open() that provides operations for interacting with an opened file.
context manager
An object used by a with statement to set up work and perform its defined cleanup when the block ends.
text stream
A stream that reads or writes character strings while handling conversion between characters and stored bytes.
encoding
A defined mapping used to represent characters as bytes and decode those bytes back into text.
newline
The \n character used in Python text to mark the end of a line.
end of file
The point at which a read operation has no more data available from a file.
iteration
Repeatedly obtaining successive items from an iterable, such as successive lines from a file object.

Sources & references

  1. The Python Tutorial — 7. Input and Output (Reading and Writing Files) — Python Software Foundation
  2. Python Library Reference — io: Core tools for working with streams — Python Software Foundation

EliExplains lessons are original prose written from the open, credible references above. See Copyright & Licensing.

Researched 2026-08-19

Educational content only. It is not medical, legal or professional advice. Found an error? Tell us.