Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pathlib vs. os.path.join in Python

Tags:

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?

like image 756
Amir Avatar asked Apr 15 '21 16:04

Amir


People also ask

Which is better os path or Pathlib?

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.

Why is Pathlib better than 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?

Does Pathlib replace os path?

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!

What is Pathlib path in Python?

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.


1 Answers

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

like image 79
wisbucky Avatar answered Sep 21 '22 15:09

wisbucky