Sometimes you may need to get current working directory while working with your python application. You can easily get this information using os python module, which is included in standard library, so you don’t need to install anything. In this article, we will look at how to get current directory in Python and how to change directory also.
How to Get Current Directory in Python
You can easily get current directory and change directory using os.getcwd() and os.chdir() functions respectively.
1. Get Current Directory
os.getcwd() function returns the absolute path of your python file as a string. It stands for get complete working directory.
Here is a simple code to demonstrate its function.
import os path = os.getcwd() print(path) # /home/ubuntu print(type(path)) # <class 'str'>
First we import os module. Then we call os.getwd() function and store its result in path variable. Then we print path variable as well as its type.
2. Change Current Working Directory
If you need to change current working directory, you can do it with os.chdir() command. You need to specify the new working directory. You may specify the new path as a absolute or relative path. Here is an example
import os print(os.getcwd()) # /home/ubuntu os.chdir('../') print(os.getcwd()) #/home os.chdir('/tmp') print(os.getcwd()) #/tmp
In the above code, first we import os module. Then we print our current working directory ‘/home/ubuntu’. Then we use os.chdir to change to parent directory, using relative path. Then we print this new working directory. Then we use os.chdir command to change directory, using absolute path. Finally, we print this new path once again.
In this article, we have learnt how to get current working directory in python and how to change the directory. You may need to get this information in case you want to perform file operations or run system commands from your python script or application.
Also read:
How to Check Dependencies for Package in Linux
How to Iterate Over Multiple Lists in Python
How to Disable GZIP Compression in Apache
How to Install Specific NPM Package Version
How to Disable TLS 1.0 in Apache
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.