When I need to define a file system path in my script, I use os.path.join
to guarantee that the path will be consistent on different file systems:
from os import path
path_1 = path.join("home", "test", "test.txt")
I also know that there is Pathlib
library that basically does the same:
from pathlib import Path
path_2 = Path("home") / "test" / "test.txt"
What is the difference between these two ways to handle paths? Which one is better?
Basically you can do it either way, it really doesn't matter much. It probably boils down to what syntax you prefer. Personally I don't like the slash being “abused” as a path concatenation operator, therefore I prefer os.
Pathlib allows you to easily iterate over that directory's content and also get files and folders that match a specific pattern. Remember the glob module that you used to import along with the os module to get paths that match a pattern?
The pathlib module replaces many of these filesystem-related os utilities with methods on the Path object. Notice that the pathlib code puts the path first because of method chaining!
The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.
pathlib
is the more modern way since Python 3.4. The documentation for pathlib says that "For low-level path manipulation on strings, you can also use the os.path module."
It doesn't make much difference for joining paths, but other path commands are more convenient with pathlib
compared to os.path
. For example, to get the "stem" (filename without extension):
os.path: splitext(basename(path))[0]
pathlib: path.stem
Also, you can use the same type of syntax (commas instead of slashes) to join paths with pathlib
as well:
path_2 = Path("home", "test", "test.txt")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With