OS Module in Python

The OS module is a module in Python that provides the best functionalities to perform a specific task. in the OS module, we have the functionality for creating and removing a directory.

By using the functionality of the OS module we can bring the data from directories and we can change and update the current working directories as well. We can also list the directories using OS module functions.

The OS module interacts with your system. The OS module functions have the ability to access and make changes in the files and directories and it can fetch the information about the files and directories from your system.

Few Important OS Module Functions

Don’t forget to import the OS module first because without importing the OS module you can’t access its functionality so make sure you have imported the OS module.

For importing the OS module use the following code.

Import os

For creating a new folder or directory use the following code.

import os

If you want to know your present working directory path so use the following code.

import os

For creating a physical directory without specifying the path, use the following code and you will see the directory in your working directory. This means the new directory will appear in ‘C:\\Python37’.

import os

As we mentioned above by using OS module functionality we can change the directory as well, so for changing your present working directory use the following commands.

Import os
>>> os.getcwd()
>>> os.chdir("..")
>>> os.getcwd()

The os.chdir command will change the directory. we used the os.chdir(“..”) command for setting the new directory. The (“..”) in command is used to convert the present directory into the parent directory. 

We can remove the directory as well by using the following code

import os

make sure the directory is empty, otherwise, it will not remove the directory. 

You can see the list of files and subdirectories by executing the following code.

import os                                      

The above command will show the list of all available files and subdirectories.

You can check the OS module name by using the following code.

Import os

If you want to rename a file so execute the following code.

import os
fileDir=”info1.txt” os.rename(fd,’inform.txt’)

You can know the process ID by executing the following code.

import os

You can access the environment variable by using the environ process parameter, see the code below.

import os
result = os.environ['HOME']


In this article, we talked about the OS Module in Python, and we also discussed its different functions for performing specific tasks.

Hope you like the tutorial if you have any queries regarding this article feel free to contact us below. Thanks for reading.

Suggested Article:

Leave a Comment