Modules are basically pre-defined functions that help to reduce the redundancy to the code and add built-in functionalities to it. Python os Module allows us to interact and use the Operating System functionality efficiently.
- The os module allows us to gain access to the Operating System information.
- Thus, this module contains functions that serve as a way to interact with the Operating System.
- The os module lets us work with the files and the directories.
1.1. Importing Python os Module
This function helps us understand the name of the os module that is imported. It differs on the basis of the operating system the user is using.
In the above snippet, the command has been run on the Windows operating system. That’s why the name of the os module imported is displayed as
nt. The output differs from Operating Systems and interpreter of different systems. If you run it on Mac OS, it will print
The output of this function varies from system to system. It is used to return the Current Working Directory (CWD) that is used to execute and run the code in python.
This function can be considered as one of the techniques to execute other commands of the system in Python.
To achieve the same, firstly we need to create a python snippet hello.py with the following code in it.
Then, create another python file file1.py and add the following code in it and run the script.
OSError is the base class for every IO related errors. So, we can use this Exception class to catch IO errors in the except block.
try: f = open('abc.txt', 'r') # file is missing except OSError: print('Catching IO Errors in OSError block')
This function makes use of the uid to check for the accessibility to a path. The method returns True if a particular file exists and access to that file is allowed, else it returns False. It takes up two arguments: path and mode. The path is the directory where the particular file is situated. The mode can have one of the following values:
In the below snippet of code, the function
os.chdir(path) changes the CWD to the path specified by the user as an argument.
This method returns the current executing process’s ID popularly known as PID.
This function returns the list of files and directories present in the CWD passed as a parameter as the argument.
This function creates a new directory from the os Module accepting the pathname as an argument.
In the below screenshot, it can be clearly seen that when the above code is run, it creates a folder with the name passed as argument i.e. ‘demo’ in the mentioned directory/drive.
In this article, we get to know about many of the functions and their implementation provided by the os module. This module is very similar to the Python sys module.