Pathlib and OS Path module in Python

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.

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)

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

Now back to pathlib, 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

pathlib makes file handling easy by allowing you to open, read and write files directly through Path objects no need for manual path strings or separate functions.

Example: This code reads overwrite "try write this text" into output.txt. Followed by appending "try write another line". Finally read content from README.txt

# old text will be overwritten
with (p / 'README.txt').open('w') as file:
    file.write("let us write this text")

# appending to a file
with (p / 'README.txt').open('a') as file:
    file.write("let us write another line")

with (p / 'README.txt').open('r') as file:
    content = file.read()
    print(content)

let us write this text
let us write another line

Not to be mistaken with PYTHONPATH

web security linux ubuntu Raspberry   git   javascript css python django drupal php apache mysql  MongoDB AWS data  ML AI