Filter Files by Extension
Advanced · Write the code · from Python pathlib: Modern File Path Handling
From the lesson: Python pathlib: Modern File Path Handling
Imagine navigating to a friend's house. You could follow vague paper directions like "turn left at the big tree, then right at the red mailbox." Or you could use GPS, which understands addresses, calculates routes, and handles all the tricky details for you.
Read the lessonGiven a list of file paths, use pathlib to filter only the .py files and print their stem (filename without extension), one per line, in alphabetical order.
File list: ['app/main.py', 'app/utils.py', 'app/data.csv', 'app/config.json', 'app/test_app.py']
Expected output:
main
test_app
utilsfrom pathlib import PurePosixPath
files = ['app/main.py', 'app/utils.py', 'app/data.csv', 'app/config.json', 'app/test_app.py']
# Your code here
More pathlib exercises
- Extract Path ComponentsBeginner
- Predict the Joined PathBeginner
- Change File ExtensionIntermediate
- Fix the Path Joining BugIntermediate
All Python exercises · 50 practice problems · File I/O & Data Formats quiz