Paths
Construct paths explicitly and distinguish the working directory from a source-file location.
On this page
The concept
A Path represents a filesystem path. The / operator combines path components without manually assembling slash-separated strings. Path.cwd() refers to the terminal's current working directory. Path(file).resolve().parent refers to the directory containing this source file. Those locations need not be equal.
TemporaryDirectory supplies a disposable directory and removes it on exit. The example creates a child folder and a small file there, so running the lesson does not leave permanent data in the course. Existence checks, filenames, suffixes, and globbing inspect filesystem structure rather than file contents.
Worked example
Extract the example files. From the python_from_zero directory, run the following command in a terminal. On Windows, use py in place of python3.
python3 06_files_and_projects/43_paths/lesson.pyfrom pathlib import Path
from tempfile import TemporaryDirectory
print("Working directory:", Path.cwd())
print("Lesson directory:", Path(__file__).resolve().parent)
with TemporaryDirectory(prefix="python_paths_") as temporary:
folder = Path(temporary) / "notes"
folder.mkdir(parents=True, exist_ok=True)
file_path = folder / "lesson.txt"
file_path.write_text("Python", encoding="utf-8")
print(file_path.name, file_path.suffix, file_path.stem)
print(folder.exists(), folder.is_dir(), file_path.is_file())
print([path.name for path in folder.glob("*.txt")])Trace the result
- Compare the two printed directories and consider how running from the course root changes cwd.
- mkdir creates the notes folder before write_text creates its file.
- name, suffix, and stem split the filename in different ways; glob selects matching paths.
Working directory: <COURSE_ROOT>/06_files_and_projects/43_paths
Lesson directory: <COURSE_ROOT>/06_files_and_projects/43_paths
lesson.txt .txt lesson
True True True
['lesson.txt']Interpreter and directory paths depend on your machine.
Line-by-line walkthrough
Line 1: from pathlib import Path
Import Path from pathlib. This supplies filesystem path values. The caller can now use the imported names directly.
Line 2: from tempfile import TemporaryDirectory
Import TemporaryDirectory from tempfile. This supplies temporary files and directories. The caller can now use the imported names directly.
Line 4: print("Working directory:", Path.cwd())
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 5: print("Lesson directory:", Path(__file__).resolve().parent)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Lines 6–13: with TemporaryDirectory(prefix="python_paths_") as temporary:
Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.
Line 7: folder = Path(temporary) / "notes"
Evaluate Path(temporary) / 'notes', then bind or update folder with the result. Assignment itself does not imply a deep copy.
Line 8: folder.mkdir(parents=True, exist_ok=True)
Call folder.mkdir to create the selected directory. This call may have an effect even when its return value is not assigned.
Line 9: file_path = folder / "lesson.txt"
Evaluate folder / 'lesson.txt', then bind or update file_path with the result. Assignment itself does not imply a deep copy.
Line 10: file_path.write_text("Python", encoding="utf-8")
Call file_path.write_text to encode and write text to the selected path. This call may have an effect even when its return value is not assigned.
Line 11: print(file_path.name, file_path.suffix, file_path.stem)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 12: print(folder.exists(), folder.is_dir(), file_path.is_file())
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 13: print([path.name for path in folder.glob("*.txt")])
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Common mistake
Relative paths are interpreted against the working directory, not automatically against the script location.