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,

Advertisements
/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.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

1 thought on “Python : Get Current Directory”

Leave a Comment

Your email address will not be published.

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

Scroll to Top