Home >Backend Development >Python Tutorial >How Do I Get the Current and Script Directories in Python?
Knowing the current directory and the location of the currently executing Python file can be useful in many scenarios. Here's how to retrieve this information:
To obtain the full path to the current working directory where you ran the Python script, use the following code:
import os cwd = os.getcwd()
To determine the directory containing the running Python file, utilize the following incantation:
import os dir_path = os.path.dirname(os.path.realpath(__file__))
This approach ensures that the correct directory is retrieved regardless of any changes made to the current working directory using os.chdir().
The above is the detailed content of How Do I Get the Current and Script Directories in Python?. For more information, please follow other related articles on the PHP Chinese website!