How to access the parent directory in Python?

You can use the os.path.abspath() function combined with the os.path.dirname() function to get the parent directory.

The sample code is as follows:

import os

current_dir = os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(os.path.join(current_dir, '..'))

print(parent_dir)

In this case, __file__ represents the path of the current script. The os.path.dirname() function is used to obtain the directory where the current script is located, the os.path.abspath() function is used to get the absolute path. The os.path.join() function is used to concatenate paths, where ‘..’ represents the parent directory.

Running the above code will output the path of the parent directory.

bannerAds