← All lessons

pathlib: paths without glue

Sign in · Sign up

Lesson 9.7

pathlib gives you handy paths:

from pathlib import Path

folder = Path("data")
folder.mkdir(exist_ok=True)

file = folder / "hello.txt"
file.write_text("Hello", encoding="utf-8")

print(file.read_text(encoding="utf-8"))
print(file.exists())
  • Path("a") / "b" joins a path — instead of gluing "/" by hand;
  • mkdir(parents=True, exist_ok=True) creates a folder together with its parents and doesn't fail if it already exists;
  • write_text and read_text write and read a small file in one line;
  • exists() and glob("*.txt") look for files.

The check sets the folder folder, the file name file and the text text. Create the folder, write the file into it with Path, then print the text from the file, True/False from exists() and the number of *.txt files found with len(list(...)).

Hint

Paths are joined with the / operator: folder / file.

mkdir(parents=True, exist_ok=True) creates the folder with its parents and doesn't fail if it already exists. write_text and read_text work with text, glob looks for files by pattern.