How can I determine the following in a Python script:
- The current directory (where I was in the shell when I ran the Python script).
- The directory where the Python file I am executing is located.
How can I determine the following in a Python script:
To get the full path to the directory a Python file is contained in, add the following code to that file:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(Note: If you’ve used os.chdir()
to change your current working directory, the value of the __file__
constant will be relative to the current working directory and won’t be affected by the os.chdir()
call.)
To get the current working directory, use:
import os
cwd = os.getcwd()
Here are the documentation references for the modules, constants, and functions used above:
__file__
constantTo get the current directory’s full path:
import os
print(os.getcwd())
Output: “C:\Users\admin\myfolder”
To get just the current directory’s folder name:
import os
str1 = os.getcwd()
str2 = str1.split('\\')
n = len(str2)
print(str2[n-1])
Output: “myfolder”
To get the directory containing the current script using the pathlib
library:
import pathlib
filepath = pathlib.Path(__file__).resolve().parent
This will give you a Path
object representing the directory containing the current script.