os.path is string-based while pathlib is object oriented
os.path operates on strings while pathilib is object oriented. So if "/home/test/test.txt" is the absolute path (in POSIX format) to access to the file test.txt in the directory /home/test/, the instructions:
from os import path
path_1 = path.join("/home", "test", "test.txt")
(executed in a Linux system) return in path_1, the string "/home/test/test.txt" (link to os.path.join() documentation.)
On the other hand the following instructions:
from pathlib import Path
path_2 = Path("/home") / "test" / "test.txt"
return an object called path_2 which represents the file.
A function and a method available with the 2 approaches
By previous initialization, essentially:
- the string
path_1 can be used as argument of other functions of the module os.path, for example:
from os import path
if path.exists(path_1):
# the file exists
- the object
path_2 is an instance of the class pathlib.Path so with this object it is possible to call all methods of the class Path; furthermore if path_2 is created on a POSIX compliant system (as Linux) its type is PosixPath (a subclass of Path) else if path_2 is created on a Windows system its type is WindowsPath (a subclass of the class Path); an example of method available on the object path_2 is exists(), and the snippet of code below shows its used:
from pathlib import Path
path_2 = Path("/home") / "test" / "test.txt"
if path_2.exists():
# the file exists
Link
See this link to know other differences between this two ways to manage path with Python.
path_2 = Path("home", "test", "test.txt")and forget about the slashos.pathorpathlib. If you've imported and are using one of them already then presumably just keep using that one to avoid additional imports and inconsistency.