How to Get the Current Directory in Python

To get the base path of your Python working directory with the os.path method, write the following within your Python file or shell:

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BASE_DIR)

However, to use the above method to check the active working directory, type the following:

import os
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
print(CURR_DIR)

Getting the current Python directory with the os.getcwd method is quite straight forward; to use it, run the following lines in your shell or Python file:

import os
CURR_DIR = os.getcwd()
print(CURR_DIR)

Switching Your Current Python Directory

You can change the current Python directory to inherit another file path if you like. To do that, you only need to define the file path for the new working directory as done in the code snippet below. Ensure that you replace the path with the one that applies to you:

import os
chd = os.chdir('C:/Users/Omisola Idowu/Desktop/my_project')
CURR_DIR = os.getcwd()
print(CURR_DIR)

The code above changes the current working directory to the one in parenthesis. Thus, the output of the snippet above returns the full path of the new directory you entered in the os.chdir() method.

Leave a Reply

Your email address will not be published. Required fields are marked *