We can use Python’s os.path
module along with os.path.dirname()
to go up one directory.
The dirname()
function returns the directory component of a pathname, which effectively removes the last component of the path.
Here’s how we can go up one directory:
import os
current_directory = os.getcwd() # Get the current working directory
parent_directory = os.path.dirname(current_directory) # Go up one directory
print("Current directory:", current_directory)
print("Parent directory:", parent_directory)
This code snippet will print the current directory and its parent directory.
The os.path.dirname()
function extracts the directory part of the current working directory path, effectively going up one level in the directory hierarchy.