Python Tutorial 0/52 lessons ~6 min read Lesson 33

    File I/O

    Open files with the with statement — it auto-closes the handle even on exceptions.

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Open files with the with statement — it auto-closes the handle even on exceptions. Choose binary mode for non-text data.

    Understanding the topic

    Core concepts to understand:

    • open(path, 'r'|'w'|'a'|'b')
    • Always use with for auto-close.
    • Text mode handles encoding; binary mode = bytes.
    • pathlib.Path for modern path handling.

    Syntax reference

    Visual flow / code:

    python
    from pathlib import Path
    # Write
    Path("hello.txt").write_text("hi\n", encoding="utf-8")
    # Read all
    text = Path("hello.txt").read_text(encoding="utf-8")
    # Stream line-by-line
    with open("big.log", encoding="utf-8") as f:
    for line in f:
    process(line)
    # Binary
    with open("img.png", "rb") as f:
    data = f.read()

    Execution workflow

    1File I/O Workflow
    1 / 4

    Step 1

    open(path, 'r'|'w'|'a'|'b')

    Apply this step while implementing file i/o in real code.

    Real-world use

    pathlib replaced os.path in modern Python — type-safe, cross-platform, with chainable methods.

    Best practices

    • Always use with.
    • Always specify encoding=.
    • Stream large files line-by-line.

    Common mistakes

    • Forgetting encoding defaults to platform — broken Unicode on Windows.

    Hands-on exercise

    Interview preparation — practice these questions:

    • Why with open(...)?
    • pathlib vs os.path?
    • Text vs binary mode?

    Summary

    In summary: with + encoding + pathlib. Stream — don't slurp.

    Ready to mark this lesson complete?Track your journey across the entire course.