Catenate The Path With Pathlib
Old Wine in New Bottles?
The solution to the earlier example by catenating the paths was:
path_file = os.sep.join([path_dir, filename])
The advantage of this is that the solution is independent of the operating system, and one does not have to combine strings with a “+” sign or string formatting.
Yet, this is error prone in that one could inadvertently or mistakenly define the directory path with a closing path separator.
path_dir: str = r"C:/Users/sselt/Documents/blog_demo/" # abschließender Trenner
filename: str = "some_file"
path_file = os.sep.join([path_dir, filename])
# C:/Users/sselt/Documents/blog_demo/\some_file
Although this example shows a functioning code, the wrong separator leads to an error when calling up the path. Such errors can occur whenever users manage the path in config files, far from the code, without paying attention to the convention.
A better solution has emerged since Python 3.4, as a pathlib module. This handles file and folder functions of Python’s os module with an object-oriented approach.
To repeat, here’s the old variant:
import os
path = "C:/Users/sselt/Documents/blog_demo/"
os.path.isdir(path)
os.path.isfile(path)
os.path.getsize(path)
And Here Is The New Alternative
from pathlib import Path
path: Path = Path("C:/Users/sselt/Documents/blog_demo/")
path.is_dir()
path.is_file()
path.stat().st_size
Both deliver exactly the same result. So, why is the second one much better?