find the parent directory of a file in python

To find the parent directory of a file in Python, you can use the os.path module. The os.path module provides a function called dirname() which returns the directory name of a file. You can use this function to get the parent directory of a file. Here's an example:

main.py
import os

file_path = '/path/to/your/file.txt'
parent_dir = os.path.dirname(file_path)

print(parent_dir)
107 chars
7 lines

This will output the parent directory of the file specified in file_path. Note that os.path.dirname() returns the parent directory of a file, not the absolute path of the directory. If you need the absolute path, you can use the os.path.abspath() function:

main.py
import os

file_path = '/path/to/your/file.txt'
parent_dir = os.path.dirname(os.path.abspath(file_path))

print(parent_dir)
124 chars
7 lines

This will output the absolute path of the parent directory of the file specified in file_path.

gistlibby LogSnag