In this tutorial, we will look at how to get the current working directory in Python.
There are a number of ways to get the current working directory. You can use the os
standard library’s getcwd()
function. Or, you can use the pathlib library’s Path.cwd()
class method. Let’s look at these methods with some examples.
1. Using the os
module
Since os
is a Python standard library, you don’t need to install it additionally. It provides a number of useful functions to interact with the operating system (for example, using functions like getcwd(), chdir(), etc to interact with the file system).
The simplest way to get the current directory in python is to use the os.getcwd()
function. It returns the absolute path of the current working directory as a string. The following is the syntax:
import os print(os.getcwd())
Output:
C:\Users\piyush\Documents\DSP\Article
You can see that we get the absolute path of the current directory returned as a string.
Additionally, you can use the os.chdir()
function to change the current working directory, for example, in the above scenario, to change the current directory to the “Documents” folder, which is two folders above the current folder “Article”, use the following syntax:
import os # change the current working directory os.chdir('..\..') # print the current working directory print(os.getcwd())
Output:
C:\Users\piyush\Documents
You can see that now the current working directory has been changed to the “Documents” folders.
2. Using the pathlib
module
You can also use the pathlib
module in python to get the current working directory. The pathlib module has been available in the standard library since Python 3.4 and comes with a number of useful functions for file handling.
You can use the Path.cwd()
function to get the current working directory. The following is the syntax:
from pathlib import Path print(Path.cwd())
Output:
C:\Users\piyush\Documents
In the above output, you can see that we get the current working directory as output. Notice that it is the “Documents” folder. This is due to the os.chdir()
command that we performed in the previous example which changed our current directory to the “Documents” folder.
For more on the pathlib’s Path.cwd() method, refer to its documentation.
With this, we come to the end of this tutorial, The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel.
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Tutorials on interacting with the file system in Python –