How to Dynamically Get Current and Parent Directories in Python
This guide demonstrates multiple Python techniques for automatically retrieving the current directory, its parent, and grand‑parent paths using the os module, helping developers avoid manual path changes when working across multiple projects.
When working with several Python projects, hard‑coding file paths can lead to errors and constant directory changes. The following examples show how to programmatically obtain the current directory, its immediate parent, and even the grand‑parent directory using the built‑in os module.
import os
print('***获取当前目录***')
print(os.getcwd()) # Current working directory
print(os.path.abspath(os.path.dirname(__file__))) # Directory of the script
print('***获取上级目录***')
print(os.path.abspath(os.path.dirname(os.path.dirname(__file__)))) # Parent of script directory
print(os.path.abspath(os.path.dirname(os.getcwd()))) # Parent of CWD
print(os.path.abspath(os.path.join(os.getcwd(), ".."))) # Another way to get parent
print('***获取上上级目录***')
print(os.path.abspath(os.path.join(os.getcwd(), "../.."))) # Grand‑parent directoryThese snippets cover three common scenarios:
Current directory: os.getcwd() returns the directory from which the script is executed, while os.path.abspath(os.path.dirname(__file__)) gives the directory containing the script file itself.
Parent directory: Combining os.path.dirname calls or using os.path.join(..., "..") yields the immediate parent directory.
Grand‑parent directory: Adding another ".." segment to the path (e.g., os.path.join(os.getcwd(), "../..")) retrieves the directory two levels up.
By integrating these methods, developers can write path‑independent code, ensuring logs or other files are always written to the correct location without manual adjustments.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
