Posted under » Python » Django on 24 Mar 2026
In Django, on the settings file we will see pathlib in action.
from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent
In this case, __file__ is actually located at your django app location. So.. it is like eg. BASE_DIR = Path("/home/ubuntu/www/adls").resolve().parent.parent
To make pathlib work with Django do the following.
from os import path BASEDIR = os.path.join(BASE_DIR)
With OS path, you can set your basename any name even if the actual dir or path does not exist in the system.
# basename function
import os
out = os.path.basename("/baze/folio")
print(out)
os.path.isdir(path) function specifies whether the path is existing directory or not.
# isdir function
import os
out = os.path.isdir("/baze/folio")
print(out)
True
Below are some examples and use cases by which we can join file paths and handle file paths. Try to avoid / after you define root. Use comma to add more paths
import os # Path 1 path = "/baze/folio" # Join various path components print(os.path.join(path, "User/Documents", "file.txt"))
Now back to pathlib. The pathlib module in Python provides an object-oriented way to work with filesystem paths. Unlike traditional os.path which treats paths as plain strings, pathlib represents them as objects, making operations like path joining, file reading/writing and checking existence much cleaner and cross-platform.
To view or list all subdirectories within a given directory, use iterdir() method and filter results using .is_dir(). Below we list all the subdirectories under the root folder = /.
from pathlib import Path
p = Path('/')
for subdir in p.iterdir():
if subdir.is_dir():
print(subdir)
To find all text files (.txt) within a folder and its subfolders, use rglob() method from pathlib. It performs a recursive search, making it easy to scan entire directory trees for specific file types.
from pathlib import Path
p = Path('/baze/folio')
files = p.rglob('*.txt')
for f in files:
print(f)
/baze/folio/img/README.txt
/baze/folio/js/vendor/jquery/LICENSE.txt
/baze/folio/js/vendor/xregexp/LICENSE.txt
pathlib makes directory navigation simple by overloading / operator. This allows you to join paths cleanly and create new Path objects without using manual string concatenation. This eg. code joins an existing path with "README.txt" to create a new path object.
sp = p / 'README.txt'
print(sp)
# Check if the path is absolute
print("Is absolute:", sp.is_absolute())
# Get the file name
print("File name:", sp.name)
# Get the extension
print("Extension:", sp.suffix)
# Get the parent directory
print("Parent directory:", sp.parent)
You will get this output
/baze/folio/img/README.txt Is absolute: True File name: README.txt Extension: .txt Parent directory: /baze/folio/img/img
One of the common use of pathlib is to open, read and write files through Path objects.
Not to be mistaken with PYTHONPATH