With each new Python release, new modules are added, and new, better ways of doing things are introduced. Although we’re accustomed to using the good old Python libraries and certain practices, it’s time to upgrade and take advantage of the new and improved modules and their features.
Pathlib instead of OS
Pathlib is undoubtedly one of the more significant additions to the Python standard library in recent years. It has been part of the standard library since Python 3.4, yet many people still use the os
module for filesystem operations.
However, compared to the older os.path
, pathlib
offers many advantages. While the os
module represents paths as raw strings, pathlib
uses an object-oriented style, making it more readable and natural to write:
from pathlib import Path
import os.path
# Old way: using os.path
two_dirs_up = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# New way: more readable with pathlib
two_dirs_up = Path(__file__).resolve().parent.parent
Treating paths as objects rather than strings also makes it possible to create a path object once and then easily inspect its attributes or perform operations on it:
readme = Path("README.md").resolve()
print(f"Absolute path…