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
    Interview Q&A included

    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

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

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

    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.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhy <code>with open(...)</code>?+

    Answer

    The with statement guarantees the file is closed when the block exits, even if an exception is raised, because the file object is a context manager whose __exit__ closes it. Without it you must call close() in a finally. Relying on garbage collection to close files is not reliable across Python implementations, and unflushed data can be lost.

    Follow-up

    How do you open two files in one with statement?
    2BeginnerQuestionpathlib vs os.path?+

    Answer

    os.path is a set of string-manipulating functions, while pathlib.Path is an object-oriented API with operators like / for joining and methods such as read_text(), exists(), and glob(). pathlib is generally more readable and handles platform differences for you. Both are in the standard library, and most APIs accept Path objects through os.PathLike.

    Follow-up

    What is the difference between PurePath and Path?
    3BeginnerQuestionText vs binary mode?+

    Answer

    Text mode (the default) decodes bytes into str using an encoding and translates newlines, while binary mode ('rb', 'wb') reads and writes raw bytes with no decoding or translation. Use binary for images, archives, and network data. For text, pass encoding='utf-8' explicitly instead of relying on the platform default.

    Follow-up

    What happens if you decode a file with the wrong encoding?

    Summary

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

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