pathlib – Get path only (no file name)

We can get the directory path from a full path that includes a file name.

For example, let’s say we have:

/home/username/file.txt

and we just want to get:

/home/username

Code

1
2
3
4
5
6
7
from pathlib import Path

full_path = Path(r"/home/username/file.txt")
path_only = full_path.parent

print(path_only)
> /home/username