Python : Get Current Directory

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 Current Directory in Python

import os

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

print(currentDirectory)

It printed the current directory. Output in our case 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,

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

print(currentDirectory)

It printed the current directory. Output in our case was,

/home/varun

Output is different this time, because we changed the current working directory.

The Complete example is as follows,

import os

# 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)

Output:

/home/varun/python/tutorials
/home/varun

Summary

We learned how to get the current directory in Python and we also saw how to change the current directory in Python. Thanks.

1 thought on “Python : Get Current Directory”

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top