Managing path using pathlib in Python

Since Python 3.4

pathlib is object oriented. It is more elegant than os.path. For example, if we need the parent folders of the currrent file, we need os.path.dirname(),

import os

print(f"file: {__file__}")
# file:

# Using os.path
os__file_absolute_path = os.path.abspath(__file__)
print(f"Using os.path:: file absolute path: {os__file_absolute_path}")
# Using os.path:: file absolute path: /home/runner/pathlib/

os__file_in_folder = os.path.dirname(os__file_absolute_path)
print(f"Using os.path:: file is in folder: {os__file_in_folder}")
# Using os.path:: file is in folder: /home/runner/pathlib

It is much more easier to get the folder using pathlib.

from pathlib import Path

print(f"file: {__file__}")
# file:

# Using pathlib
path__file = Path(__file__)
print(f"Using pathlib:: path__file: {path__file}; using .resolve method: {path__file.resolve()}")
# Using pathlib:: path__file:; using .resolve method: /home/runner/pathlib/

path__file_in_folder = path__file.resolve().parent
print(f"Using pathlib:: path__file_in_folder: {path__file_in_folder}")
# Using pathlib:: path__file_in_folder: /home/runner/pathlib

pathlib also supports glob.

The full code is avaible on

Planted: by ;

LM (2021). 'Managing path using pathlib in Python', Datumorphism, 07 April. Available at: