Modernize your Python codebase with pathlib
The pathlib module has been part of the Python Standard Library since version 3.4, released over a decade ago. Yet, it’s still common to encounter Python codebases using the older os.path.
Let me introduce three common patterns that can be simplified using pathlib.
Constructing a Path
Instead of using:
import os
filename = os.path.join("/path", "to", "file")
You can use:
from pathlib import Path
filepath = Path("/path", "to", "file")
It’s a bit more compact, and you end up with a Path type instead of a str, expliciting this variable holds filesystem path and not just a string.
There is also a construction where you can build path using / (like Path("/path") / "to" / "file") but personaly I feel this overloading of the / operator is a bit hacky. It can however be convenient to extend an existing path (path = existing_path / "dir" )
Check existence
It’s common to want to check if a file exists before taking operations on it.
After getting your Path instance, you get access to a set of convient method to test its existence and type. First the exists() method, but also is_file, is_dir, is_symlink and all the exotic filetypes who can find on your favorite operating system.
No more need to os.path.exists.
Write, and read
It’s also quite common to want to read fully a file to a variable, or write it fully from a variable.
The proper classic construction is:
with open("/path/to/file", "r") as fd:
content = "".join(fd.readlines())
It allows to extract the full file content to the content variable and ensure proper closing of the file after exiting the context manager.
But it’s a bit verbose, why not try :
from pathlib import Path
path = Path("/path", "to", "file")
content = path.read_text()
You will get the same result.
Writing has its counterpart : path.write_text("hello world")
Hope you will enjoy using pathlib if you are not already doing it 👍
To get more information → https://docs.python.org/3/library/pathlib.html
By Thomas Martin
Follow me or comment