Intermediate LevelPython
Why is pathlib.Path superior to legacy os.path and glob for object-oriented filesystem manipulation?
❓ Interview Prompt: Explain `pathlib.Path`, object-oriented filesystem paths, overloaded `/` operator, `.read_text()`, and cross-platform compatibility.
Introduced in Python 3.4, 'pathlib' replaces legacy 'os.path' strings with clean, object-oriented 'Path' objects:
Advantages:
•
Overloads the '/' slash operator for cross-platform path joining.
•
Provides built-in methods ('p.read_text()', 'p.write_bytes()', 'p.mkdir()', 'p.glob()').
Code Implementation Example
python
from pathlib import Path
# Object-oriented path joining using / operator
base_dir = Path('/var/log')
log_file = base_dir / 'app' / 'server.log'
# Check existence and write text in one step!
if not log_file.parent.exists():
log_file.parent.mkdir(parents=True)
log_file.write_text('Log initialized')💡Navigating and manipulating filesystems using pathlib.Path.
🎯 Interview Key Takeaway
Use pathlib.Path instead of legacy os.path functions for readable, cross-platform path operations.
#pathlib#Path#Filesystem#Intermediate
Back to all Python Questions→