How can I determine the current directory and the directory of the Python file being executed in a Python script?

How can I determine the following in a Python script:

  1. The current directory (where I was in the shell when I ran the Python script).
  2. The directory where the Python file I am executing is located.

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:

  • os module
  • __file__ constant
  • os.path.realpath(path) (returns “the canonical path of the specified filename, eliminating any symbolic links encountered in the path”)
  • os.path.dirname(path) (returns “the directory name of pathname path”)
  • os.getcwd() (returns “a string representing the current working directory”)
  • os.chdir(path) (“change the current working directory to path”)

To 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.