Basic

Paths and folders

A path is a string with rules. Splitting it, joining it, and testing it are the operations that make code work on any machine.

What you will see

5

About 1 min of reading

Try It

Build and inspect paths.

1

Joined path.

import os print(os.path.join("data", "in.txt"))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
data/in.txt
2

Extension.

import os name, ext = os.path.splitext("a/b.txt") print(ext)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
.txt
3

Missing path.

import os print(os.path.exists("nope.txt"))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
False
4

Name length.

name = "x" * 5 print(len(name))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
5

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

Paths are strings with rules. Join builds the separator, splitext takes the extension, and a check is not a guarantee.
1 join the parts
↓
2 name the file
↓
3 open it
↓
4 handle the failure
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 os sets nothing on screen
print(os.path.join("data", "in.txt")) data/in.txt
Why this works
Separators differ

The separator between folders is a platform detail. Join builds it for you, which is why hand-glued paths break when code travels.

Testing is not opening

A file can pass a check and still fail to open, because something changed in between. Handle the failure at the open.

Examples

Join, do not glue

import os
print(os.path.join("data", "in.txt"))

Join adds the separator this machine uses. Gluing with a slash breaks on a different one.

Split a path

import os
name, ext = os.path.splitext("a/b.txt")
print(ext)

The extension is the last dot onward. Names can contain dots, so take it from the end.

Ask before you open

import os
print(os.path.exists("nope.txt"))

A check then an open still races. Use it for messages, not for control.

Make a folder

import os
os.makedirs("a/b", exist_ok=True)
print("made")

makedirs builds every level. exist_ok keeps an existing folder from failing.

List a folder

import os
names = sorted(os.listdir("."))
print(len(names))

Listing gives names, not paths. Join each one before opening.

A path that is too long

name = "x" * 5
print(len(name))

Filesystems cap name length. A generated name can hit the cap and fail.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Line endings
Previous Lesson
Line endings
Next Lesson
When the file is missing
When the file is missing →