Search code examples
pythonpathos.pathpathlib

Pathlib vs. os.path.join in Python


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?


Solution

  • 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")