🚀 Alguni Start learning

Unit 20: Folders & Paths

Finding your way around.

Unit 20 of 31 in Python for kids. Its 4 lessons are Paths as Objects, Making Folders, Looking Inside and Folder Master — below is everything each one explains, and a question or two from it to try.

Every sample on this page was run through real Python before it shipped, and prints exactly what it says it prints.

This unit opens with a fortnight’s trial of everything — no card needed — or with a family plan, bought in the iPhone app. The first two units of every track are free for ever. Try it in the app.

🧭 Paths as Objects

A path that knows things about itself

A filename is just text, and text cannot answer questions. A Path from the pathlib module can — whether it exists, what it is called, what kind of file it is.

Python

from pathlib import Path

p = Path("story.txt")
print(p.name)
print(p.suffix)
print(p.exists())

It prints

story.txt
.txt
False

Reading and writing in one line

write_text and read_text do the whole job — opening, writing and closing — without a with block.

Python

from pathlib import Path

p = Path("hello.txt")
p.write_text("Hi there\n")
print(p.read_text().strip())
print(p.exists())

It prints

Hi there
True

Joining with a slash

A / between paths joins them — and it gets the separator right on every kind of computer, which glueing text together does not.

Python

from pathlib import Path

folder = Path("photos")
picture = folder / "cat.png"
print(picture)
print(picture.name)

It prints

photos/cat.png
cat.png

Try it yourself

Why use Path instead of a plain string filename?

  • It is shorter to type
  • A Path can answer questions about itself and join safely onto other paths
  • Strings do not work for filenames
  • It is required in Python 3

What does this print?

Python

from pathlib import Path

p = Path("notes") / "day1.md"
print(p.suffix)
print(p.stem)

Answer them in the app

📁 Making Folders

A folder to keep things in

mkdir makes a folder. exist_ok=True means "do not complain if it is already there", which saves checking first.

Python

from pathlib import Path

folder = Path("homework")
folder.mkdir(exist_ok=True)
print(folder.exists())
print(folder.is_dir())

It prints

True
True

Putting files inside

Join the folder to a filename with /, and write as usual.

Python

from pathlib import Path

folder = Path("homework")
folder.mkdir(exist_ok=True)
(folder / "maths.txt").write_text("sums\n")
print((folder / "maths.txt").read_text().strip())

It prints

sums

Folders inside folders

parents=True makes every folder along the way, so you can build a whole path at once.

Python

from pathlib import Path

p = Path("school/year6/art")
p.mkdir(parents=True, exist_ok=True)
print(p.exists())

It prints

True

Try it yourself

What does exist_ok=True do?

  • Deletes the folder first
  • Stops it complaining when the folder is already there
  • Makes the folder hidden
  • Checks the folder is empty

Answer it in the app

🔦 Looking Inside

What is in there?

iterdir walks through everything in a folder. Sort the names, because the order the computer hands them back in is not guaranteed.

Python

from pathlib import Path

folder = Path("box")
folder.mkdir(exist_ok=True)
(folder / "b.txt").write_text("2")
(folder / "a.txt").write_text("1")

print(sorted(f.name for f in folder.iterdir()))

It prints

['a.txt', 'b.txt']

Only the ones you want

glob matches a pattern. * means "anything", so *.txt finds every text file and ignores the rest.

Python

from pathlib import Path

folder = Path("box")
folder.mkdir(exist_ok=True)
(folder / "note.txt").write_text("a")
(folder / "photo.png").write_text("b")

print(sorted(f.name for f in folder.glob("*.txt")))

It prints

['note.txt']

The older way you will still see

os.listdir does much the same thing and turns up in a lot of code. It gives plain text names rather than paths, so you have to join them back on yourself.

Python

import os
from pathlib import Path

Path("box").mkdir(exist_ok=True)
(Path("box") / "a.txt").write_text("1")

print(sorted(os.listdir("box")))

It prints

['a.txt']

Try it yourself

What does the * in "*.txt" mean?

  • Multiply
  • Any name at all, as long as it ends in .txt
  • Exactly one letter
  • All folders

Answer it in the app

🏆 Folder Master

Try it yourself

What does this print?

Python

from pathlib import Path

p = Path("music") / "song.mp3"
print(p.stem)
print(p.suffix)
print(p.parent)

Answer it in the app