Use os.getcwd() and __file__ with os.path or pathlib
To determine both the current working directory and the script’s file location:
import os
cwd = os.getcwd()
print("Current working directory:", cwd)
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
print("Directory of the script file:", script_dir)
Example:
import os
print("Current working directory:", os.getcwd())
print("Directory of this script file:", os.path.dirname(os.path.abspath(__file__)))
from pathlib import Path
cwd = Path.cwd()
script_dir = Path(__file__).resolve().parent
print("Current working directory:", cwd)
print("Directory of the script file:", script_dir)
Notes:
Work with our skilled Python developers to accelerate your project and boost its performance.
Hire Python Developers