53

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?

Amir
  • 1,926
  • 3
  • 23
  • 40
  • 3
    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.path.join, but it’s really just a matter of taste. – inof Apr 15 '21 at 16:43
  • 1
    As far as functionality goes, both do the same thing. It's mostly a matter of preference which one you like. https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/ – Pranav Hosangadi Apr 15 '21 at 16:46
  • 7
    You can do the same as `path_2 = Path("home", "test", "test.txt")` and forget about the slash – scientific_explorer Jun 22 '21 at 05:54

1 Answers1

62

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

wisbucky
  • 33,218
  • 10
  • 150
  • 101
  • 12
    One issue with pathlib.path is when working with bucket `gc://` or `s3://` `pathlib` causes the prefix to be reduce to `gc:/` etc. so better to work with os.join – skibee Nov 08 '21 at 08:44
  • 11
    @skibee In this case you can also use `cloudpathlib` – Karol Zlot Jan 20 '22 at 11:05