Skip to content
Learn Netverks

Lesson

Step 24/36 67% through track

file-io-python

File I/O

Last reviewed Jun 1, 2026 Content v20260601
Track mode
server_script
Means
Server runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches File I/O: the syntax, patterns, and safety habits you need before advancing in Python.

Teams still ship File I/O in Python codebases—skipping it leaves gaps in debugging and code reviews.

You will apply File I/O in contexts like: ETL scripts, log ingestion, and config-driven automation.

Write Python 3 in the editor and click Run on server—the dev runner executes your script with print() for output; stdlib only in playground snippets (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Python reads and writes files with built-in open() and context managers. Text mode handles encoding; binary mode returns bytes—essential for images and compressed data.

Reading and writing text

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")

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

with ensures files close even when exceptions occur—like using in C# or try-with-resources in Java.

Line iteration

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

Important interview questions and answers

  1. Q: Why use with open?
    A: Guarantees file closure via context manager protocol—prevents descriptor leaks.
  2. Q: Text vs binary mode?
    A: Text decodes/encodes with encoding; binary reads raw bytes without newline translation.

Self-check

  1. What mode writes a new text file?
  2. Why specify encoding="utf-8"?

Tip: Always specify encoding="utf-8" for text files—avoid platform-default surprises.

Interview prep

Why with open?

Context manager closes file even on exceptions—prevents descriptor leaks.

Text vs binary mode?

Text returns str with encoding; binary returns bytes without newline translation.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • with open why?
  • Text vs binary?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump