Summary - Pathlib
- Python course
- Intermediate
- Lesson 81/116
- 5 min
Combine Path, / and glob to write a file scanner.
Summary - Pathlib
In this group you learned the pathlib module. The Path class represents path objects; the / operator joins them. The .name, .stem, .suffix, .parent attributes give parts of the path.
For checking you use exists(), is_file(), is_dir(); for files write_text and read_text; for folders mkdir and rmdir; for searching glob and rglob. This module makes file operations object-oriented and safe.
Mini task: write and read a file
In the summary task you create a file on a Path object, write to it, check existence and read it back. This uses all the methods you learned together.
At the end the file existence prints True, the file type True and the content "hello world". These outputs show the operation succeeded.
Practice Write, check and read a file
Start with from pathlib import Path. Create a path with p = Path("summary.txt"). Write with p.write_text("hello world", encoding="utf-8"). Check with print(p.exists()) and print(p.is_file()). Finally print the content with print(p.read_text(encoding="utf-8")).
Starter code
# Import the Path class
# Create p, write with write_text
# Check with exists and is_file
# Print the content with read_textSample solution
# Import the Path class
from pathlib import Path
# Create p, write with write_text
p = Path("summary.txt")
p.write_text("hello world", encoding="utf-8")
# Check with exists and is_file
print(p.exists())
print(p.is_file())
# Print the content with read_text
print(p.read_text(encoding="utf-8"))Expected output
True True hello world
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which operator joins two paths?
- +
- *
- / Correct answer
- &
Explanation: The / operator joins two Path objects or a Path with a string.
2 Complete the exists call
from pathlib import Path
p = Path("f.txt")
print(p.____())
from pathlib import Path
p = Path("f.txt")
print(p.exists())
Explanation: exists() checks existence.
3 Match the pathlib methods
| Term | Meaning |
|---|---|
mkdir |
Creates a folder |
glob |
Finds files by pattern |
exists |
Existence check |
write_text |
Writes text to a file |