smartyfy.mrindigi.com

Python Master Course V2 — 072. Reading Text Files

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 07 · LESSON 072 OF 200

Reading Text Files

Study time: 75–100 minutes · Prerequisites: functions, exceptions, pathlib and Lesson 71.

Course hub

Video lesson

Video not yet available. Reserved for a verified lesson video URL/player.

Learning outcomes

Read UTF-8 documents safely. You will also identify failure cases, predict outputs, apply the concept in a small application, and test the result.

Understand Reading Text Files

Decode bytes using a known encoding

A text file stores bytes; reading in text mode converts those bytes into Python strings using an encoding. Specify UTF-8 when that is the file’s documented encoding instead of relying on machine-specific defaults. The reader cannot infer every arbitrary encoding safely. A UnicodeDecodeError means the bytes do not fit the selected decoding rules; it does not mean the file is empty or that silently removing characters is a reliable repair.

Use a with statement to ensure the file closes when processing finishes, including when an exception interrupts the loop. read() loads the remaining text, readline() reads one line and iterating the open file yields lines progressively. For a large log, iteration avoids storing the entire text at once. Memory still depends on the largest line and whatever results the program keeps; streaming does not make every possible workload constant-memory.

Python
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temporary:
    path = Path(temporary) / "notes.txt"
    path.write_text("  alpha  \n\nβeta\n", encoding="utf-8")
    with path.open("r", encoding="utf-8") as source:
        lines = [line.removesuffix("\n") for line in source]
    print(lines)
    print(len(lines))
Expected output
['  alpha  ', '', 'βeta']
3

Remove only the characters your format permits

With the normal universal-newline behavior of text files, common line endings are translated to newline characters when read. removesuffix("\n") removes one trailing newline while preserving the spaces around alpha. strip() removes all leading and trailing whitespace, which would change meaningful indentation or padding. Use strip when the rule is explicitly “ignore surrounding whitespace”, not as an automatic cleanup for every text format.

A blank line is still a line. The fixture contains one between alpha and βeta, so the list includes an empty string. A final newline does not invent an additional content line when iterating this file. A last line without a newline must also be processed; do not assume every record ends with one. Decide separately whether blank or whitespace-only lines count toward the report.

Count nonempty lines without keeping them all

Reusable function: whitespace-only lines do not count
def count_nonempty(path):
    count = 0
    with path.open("r", encoding="utf-8") as source:
        for line in source:
            if line.strip():
                count += 1
    return count

Applied inside the temporary-directory block after the fixture is written, print(count_nonempty(path)) prints 2. This function keeps a count instead of accumulating every line. It lets read and decoding errors propagate to the caller, where a command-line program can report the filename and the specific failure. Catching an error and returning zero would confuse an unreadable file with a genuinely empty one.

An open file has a current position. After a complete loop or read, another read normally returns an empty string because the cursor is at end-of-file. Reopen the file for a fresh pass, or deliberately seek back to the beginning when working with a seekable file. Reusing a consumed stream without resetting it is a common cause of unexpectedly empty processing.

For the log-reader project, test an empty file, whitespace-only lines, a final line without a newline, valid Unicode and invalid UTF-8 bytes. Report FileNotFoundError and PermissionError distinctly from decoding failures when those cases need different recovery. Preserve the source bytes while diagnosing the encoding. See the open documentation for encoding and newline behavior.

Progressive runnable Python example

Requires Python 3.10+. Run in a disposable practice folder. Save as lesson72.py and execute with python lesson72.py or python3.

from pathlib import Path
p=Path('lesson72.txt')
p.write_text('alpha\nbeta\n',encoding='utf-8')
with p.open(encoding='utf-8') as f:
    print([line.strip() for line in f])

Expected output:

['alpha', 'beta']

How to reason through the example

Identify which operation opens, parses, writes or transforms data. Trace each value from source to output. Note whether any file is created and whether repeated execution changes the result. Next, alter one value, predict the result, run the example and compare your prediction.

Additional code exercise — Streaming count

from pathlib import Path
from tempfile import TemporaryDirectory

def count_nonempty(path):
    with path.open(encoding="utf-8") as source:
        return sum(1 for line in source if line.strip())

with TemporaryDirectory() as temporary:
    path = Path(temporary) / "log.txt"
    path.write_text("one\n   \ntwo", encoding="utf-8")
    assert count_nonempty(path) == 2
    print(count_nonempty(path))

Expected: 2. The final nonempty line has no newline; it still counts. The fixture is removed automatically.

Guided practical project

Project brief: Build a text-log reader that counts nonempty lines and reports unreadable files.

  1. Specify input format, accepted fields and error policy.
  2. Create a small sample dataset with three valid and two invalid records.
  3. Write a parser and validator that report errors with record numbers.
  4. Implement the transformation as a separate testable function.
  5. Write results to a different destination rather than overwriting source files.
  6. Test empty, malformed, boundary and ordinary cases.
  7. Document setup, expected output and recovery procedure.

Mastery requirements: at least three automated tests, explicit error handling and a reproducible example. This is an assignment, not a claim that the complete project has been executed on the website.

Common mistakes and debugging

  • Assuming the process working directory is the same as the script directory.
  • Relying on platform-dependent encodings.
  • Trusting records without checking required fields or types.
  • Overwriting input files before verifying transformed output.
  • Catching every exception and hiding the underlying failure.

Debug systematically: reproduce a failure with the smallest record, inspect the exception and offending input, correct the cause, and add a regression test.

Practice and explained answers

Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.

Optional hint for question 1

Think about what each approach keeps in memory and whether both advance the stream cursor.

1. What is the difference between read and iterating a text file?

Answer and reasoning:

read loads the remaining contents into one string. Iteration yields lines progressively, allowing a counter or filter to process them without keeping the whole file. Both advance the file’s current position.

2. Why does line.strip() alter more than the newline?

Answer and reasoning:

It removes leading and trailing whitespace, including spaces and tabs. For a format where indentation matters, remove only the line ending, such as line.removesuffix("\n") after normal text newline translation.

3. What should an unreadable file contribute to a nonempty-line count?

Answer and reasoning:

It should produce an explicit error or rejected-file result, not a fabricated count of zero. Zero means successfully read with no qualifying lines; an access or decoding failure is unknown data.

4. Why is the second read empty?

Answer and reasoning:

Python
from io import StringIO

source = StringIO("alpha\nbeta\n")
print(repr(source.read()))
print(repr(source.read()))
Expected output
'alpha\nbeta\n'
''

The first read consumes the stream to its end. Call seek(0) on this seekable in-memory stream or create a fresh stream to read from the beginning again.

5. Repair the original two-line fixture.

Answer and reasoning:

Python
text = "alpha\nbeta\n"
print(text.splitlines())
Expected output
['alpha', 'beta']

The backslash-n escape represents an actual line break in the string. The earlier literal alphanbetan contained letters n, so it could not produce two lines.

Knowledge check

Use the topic-specific practice questions above to check your understanding. Attempt each answer before opening its explanation.

Return to the practice questions ↑

Mastery checkpoint

Demonstrate the sample, explain its output, implement the project, test three edge cases, and describe your error-handling policy. The video remains unavailable and learner completion is not account-synchronized.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.