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,
Frequently Asked:
/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.
Best Resources to Learn Python:
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.
Leave a Reply
You must be logged in to post a comment.