Python pathlib
The place of a file and the words inside it are different things. plate.txt can hold the word bread. A path only says which folder, and which name. On this page you build that place. You do not open the file, and you do not write anything into it.
from pathlib import Path
meal = Path("kitchen") / "soup.txt"
print(meal.name)
print(meal.parent)
The screen shows soup.txt, then kitchen. meal.name is only the last piece, so kitchen does not appear on that line. meal.parent is only the folder, so soup.txt does not appear on that line. The slash joins Path("kitchen") and the name soup.txt. That slash is not division. This program has no write, no open, and no close. Nothing is stored in a file.
from pathlib import Path
only = Path("soup.txt")
print(only.name)
print(only.parent)
The screen shows soup.txt, then a single dot. only.name is still the file name. only.parent is a dot because this path names no folder of its own. The dot means the folder you are already in. soup.txt is not created. If that file is missing, these lines still run. Building a path does not read the file, and a missing file does not stop it.
A slash between two plain pieces does stop the program. "kitchen" / "soup.txt" is not a path: neither side is a Path, so that slash is division, and the stop is a TypeError. Keep Path on the left. The next page is JSON. This page only names the place.
The path names the place
meal.name is soup.txt. meal.parent is kitchen. When the path has no folder, the parent is a dot. The file is not created, and a missing file does not stop these lines. The slash joins a Path to a name. The next page is JSON.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top