In this article we will discuss how to get the current working directory in Python.

Python’s os module provides a function to get the current working directory i.e.

os.getcwd()

It returns a string containing the current working directory.

For calling this function we need to import os module i.e.

import os

Let’s understand by an example,

Get the Current Working Directory in Python

'''
    Get Current working Directory
'''
currentDirectory = os.getcwd()

It will return the current working directory. In our system output was,
/home/varun/python/tutorials

Let’s change the current working directory to ” .
'''
    Change the Current working Directory
'''
os.chdir('/home/varun')

Now let’s get the current working directory,
currentDirectory = os.getcwd()

Now output in our system was,
/home/varun

because we changed the current working directory.

Complete example is as follows,

import os

def main():
    
    '''
        Get Current working Directory
    '''
    currentDirectory = os.getcwd()
    
    print(currentDirectory)
    
    '''
        Change the Current working Directory
    '''
    os.chdir('/home/varun')
    
    '''
        Get Current working Directory
    '''
    currentDirectory = os.getcwd()
    
    print(currentDirectory)
        
if __name__ == '__main__':
    main()


Output:
/home/varun/python/tutorials
/home/varun