GCGrowCarrer

File I/O

Locked

Lesson 14 of 60 · Syntax · Medium

Finish these first:Exceptions →Or pass the tests below to unlock it now.

1

The big idea

Open files with a context manager so they always close. Use pathlib.Path for paths and handle FileNotFoundError.

Think of it like this: Think of syntax and expressions like labeled measuring cups in a kitchen: each cup holds a specific kind of ingredient, and operators combine them into a new measurement.
Key words (tap to learn):
2

Read the lesson

Open files with a context manager so they always close.

with open("data.txt", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip())
with open("out.txt", "w") as f:
    f.write("hello\n")

Use pathlib.Path for paths and handle FileNotFoundError.

3

Quick check

Before writing code: What should `count_lines('/definitely/missing.txt')` return when your implementation of File I/O is working?

4

Your challenge

2 sample tests, 1 hidden

Write count_lines(path) returning the number of lines, or 0 if the file is missing.

Stuck? Get a hint (free)
More learning tools(compare languages, visual guide, related lessons)

Compare with another language

Similar to java.file-io-nio (80% overlap). `with open()` ~ try-with-resources + `Files`/`Path`.

Visual walkthrough

A diagram, a step-by-step animation, and short captions for File I/O.

Mastery0%

Learn this first

Opens up next