Scripting

Python Get Current Directory

Python Get Current Directory

When working with python files in directories, it is recommended to use absolute file paths. However, if you are dealing with the relative paths then, you must have a better understanding of the current working directory and how to get the current directory in python. The absolute and relative paths are different from each other. The relative path always begins from the current directory, while the absolute path represents a file directory location that starts from the root directory.

To get a current working directory, the os python module is used that helps to interact with the operating system. This module is a part of the standard python library and includes all the methods required to find the current working directory.

We will go through in this tutorial how to get the current python directory.

Get current directory in Python using os.getcwd() method

In order to get the python current directory via the terminal, Open the terminal using the ‘Ctrl+Alt+t’ keys and make sure that python should be installed on your system. Now, import the os python module by using the following command:

>>> import os

Use the getcwd() method that returns a string that prints the absolute path of the current directory. The returned string will not show the slash characters.

>>> os.getcwd()

The following output shows on the terminal window if you get python current directory path through the terminal:

Example

Let’s explain the above method with the help of an example which is mentioned below:

Create a python script file. Open an empty text file and paste the following source code in this file:

# Import os module

import os

# Get current python directory

cwd = os.getcwd()

# display current python directory

print("Current working directory: {0}".format(cwd))

# Display the returned object type

print("os.getcwd() returns an object of type: {0}".format(type(cwd)))

Now, save the above file with the ‘.py’ extension with some suitable name.

In the above source code, the os module is imported at the top of the file, and then using this module gets the current directory path. Execute this python file through the terminal by running the following command:

$ python file-name.py

Here, the file name is ‘getdirectory.py’. So, change the above command into the following form:

$ python getdirectory.py

The following python current directory shows on the terminal:

Conclusion

We have studied in this article, by using the ‘os. getcwd()’ method you can easily get the python current working directory. We have also mentioned an example to explain the current directory concept. Moreover, you can also explore more uses of the os.getcwd() method through internet resources. I hope the above-explained information will provide you a complete guide to get the python current working directory.

Similar Posts