find the root directory of a directory in python

You can use the os.path module in Python to find the root directory of a directory. The root directory is the top level directory of the file system in which the directory resides. Here's an example:

main.py
import os

def find_root_directory(directory):
    """
    Given a directory path, return the root directory path.
    """
    return os.path.abspath(os.path.join(directory, os.pardir))

# Example usage:
directory = "/home/user/documents/python"
root_directory = find_root_directory(directory)
print(root_directory)
316 chars
13 lines

In this example, find_root_directory takes a directory path as input and returns the root directory path using os.path.abspath and os.path.join. The os.pardir constant is used to reference the parent directory in the path.

related categories

gistlibby LogSnag