Before you run it, say out loud what it will print. Then open the answer.
What it prints
a/x.txt
3
Files kept.
names = ["a.txt", "b.bin"]
keep = [x for x in names if x.endswith(".txt")]
print(len(keep))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
1
4
Total characters.
n = 0
for line in ["a", "b"]:
n += len(line)
print(n)
Before you run it, say out loud what it will print. Then open the answer.
What it prints
2
Put it in order
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Data Flow
A file tool walks, joins paths, filters, streams each file, and reports every skip with a reason and an exit code.
1walk the tree
↓
2join and filter
↓
3stream each file
↓
4report skips and exit
Line by line
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
import ossets nothing on screen
n = 0sets nothing on screen
for root, dirs, files in os.walk("."):sets nothing on screen
n += len(files)sets nothing on screen
print(n > 0)True
Why this worksTotals need skips
A tool that counts files must count skips too. A total that ignores them is a wrong answer that looks right.
The exit code is the contract
A person sees the message, a script sees the exit code. Set both, or a caller trusts a broken run.
Examples
Walk and report
import os
n = 0for root, dirs, files in os.walk("."):
n += len(files)
print(n > 0)
The walk gives names, not paths. Join each name to its folder before opening.