Explain Codes LogoExplain Codes Logo

Using Python's os.path, how do I go up one directory?

python
path-manipulation
cross-platform
reusable-functions
Anton ShumikhinbyAnton Shumikhin·Aug 3, 2024
TLDR

No dilly-dallying, here's your answer ASAP: to go one directory up, os.path.dirname is your friend. Most keyboard-happy (or lazy) coders' first instinct:

import os parent_dir = os.path.dirname('/path/to/your/directory')

Now parent_dir is your directory's daddy, or simply the path up one level.

Back to basics: cross-platform compatibility, normalized paths, and more

First things first, always import os, the supernatural genie granting your path manipulation wishes.

Cross-platform compatibility: Use os.pardir

You want your code to play nice with Unix, macOS, Windows, or that alien OS no one else uses. os.pardir is better than '..' for parent directory reference:

import os up_one = os.path.join(os.path.dirname(__file__), os.pardir)

Comment: 'file' claims "I always know where I am!". Convenience much!

Clean up the mess: Use os.path.normpath

Say no to messy paths! Achieve Zen-level path clarity with os.path.normpath. It cleans, sweeps, and tidies up your path:

import os normalized_path = os.path.normpath(os.path.join(directory, os.pardir))

Django projects: Directing the BASE_DIR

In Django-land, the BASE_DIR often acts like headquarters. Set it to coordinate paths and locate the elusive templates folder:

import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Comment: The dancing Django changes its steps with versions, so keep up!

A touch of modern: pathlib

By the Python gods, pathlib is the new-age object-oriented way to handle paths for Python 3.4 and upwards:

from pathlib import Path parent_dir = Path('/path/to/your/directory').parent

If you've landed in Wonderland where a path is not really a path (read: symbolic links), reel it in with os.path.realpath:

import os real_path = os.path.dirname(os.path.realpath(__file__))

Efficiency upgrade: Reusable functions

Be smart, be DRY (Don't Repeat Yourself) - encapsulate your go-to-parent-directory logic in a reusable function:

import os def get_parent_dir(path): return os.path.abspath(os.path.join(path, os.pardir)) parent_dir = get_parent_dir(current_dir)

Comment: Future you thanks present you!

Check your current whereabouts: os.getcwd()

Forgot where you are? Happens to the best of us, especially in long scripts. Here's your GPS - os.getcwd():

import os current_working_dir = os.getcwd()

Comment: "Honey, where on disk are we?"

Climbing multiple levels with pathlib

Scaling more than one parent directory aka multilevel directory hopping? Use the pathlib parents attribute:

from pathlib import Path p = Path('/level1/level2/level3/level4') two_levels_up = p.parents[1] # Lands you at '/level1/level2'