OS Module in Python
What is a module?
The Modules are the kind of files that contains python statements and definitions. The module is known by the name of the file followed by the suffix “.py”. It can define variables, functions, and classes. It helps in making code easy to use and easier to understand by grouping all code related to each other into a common module. Thus, the code appears organized logically.
What is the role of the OS Module?
The OD Module in the programming world is used to interact with the operating system. It is one of Python’s standard utility modules.
Handling the current working directory:
The current working directory is also known as CWD. In python, when we try to call or open any folder, this operation gets executed successfully only if that file is available in Python’s CWD.
The current directory is the folder where the Python script runs. The python script does not lie in this directory.
Getting the Current Working Directory:
The get.cwd( ) function is used to get the location of the current working directory.
Example to illustrate this function:
# Python program to illustrate the getcwd ( ) function
# Importing the OS module
from os import *
# Getting CWD (the current working directory)
curr = getcwd()
# Returning the CWD
print("The location of the Current Working Directory is:", curr)
Output:

Changing the Current Working Directory:
The chdir( ) function is used to change the current working directory. This function changes the CWD to the path specified by the user. This function takes a single argument, i.e., the path of the new directory.
Example to illustrate this function:
# A program in Python to change the path of
# the current working directory
from os import *
# Creating a function to get the current working directory
def cur_dir( ):
print("Current working directory before updating is: \n")
print( getcwd( ) )
print( )
def nw_cur_dir( ):
print("Current working directory after updating is: \n")
print( getcwd( ) )
print( )
# Main code
# Returning the CWD before changing
Cur_dir( )
# Changing the Current Working Directory
chdir( '../' )
# Returning the CWD after changing
nw_Cur_dir( )
Output:

Creating a new directory:
Multiple methods can be used to create a new directory, and the OS module helps in doing so. The methods to create a new directory are:
- The mkdir( ) method
- The makedirs( ) method
Using the mkdir( ) method to create a new directory:
In Python programming language, if we want to create a new directory named path with the numeric mode set according to the users choice, we use the mkdir( ) method. The FileExistsError is raised by this method if the directory we are trying to create already exists.
Example to illustrate the mkdir( ) method:
# Importing the OS module
from os import *
# Naming new directory
dir = "Heyy There"
# The parent directory path
prt_dir = "C:/Users/Shailendra/"
# Initialising new path
pth = path.join(prt_dir, dir )
# Creating the new directory
# 'java T point' in
# '/home / User / Documents'
mkdir( pth )
print("New directory named '% s' created" % dir )
# Directory
dir = "Intern"
# Parent Directory path
prt_dir = "C:/Users/Shailendra/"
# Mode
mode = 0o666
# Initialising new path
pth = path.join(prt_dir, dir )
# Creating the new directory
# ‘Intern’ in
# '/home / User / Documents'
# with mode as 0o666
mkdir(path, mode)
print("New directory named '% s' created" % dir )
Output:
New directory named 'Heyy There' created
New directory named 'Intern' created
Using the makedirs( ) method to create a new directory:
If we want to create a new directory recursively, we use the makedirs( ) method. This comes in handy when we are creating a leaf directory but some of the intermediate-level directories are missing, then this method creates all those missing directories.
Example to illustrate the makedirs( ) method:
# Importing the OS module
from os import *
# Naming the leaf directory
dir = "Shailendra"
# The parent directory path
prt_dir = "C:/Users/Shailendra/javaTpoint/Nw_Project"
# Initialising new path
pth = path.join(prt_dir, dir )
# Create the leaf directory
# 'Shailendra'
makedirs( pth )
print("The new directory named '% s' created" % dir )
# Directory ‘javaTpoint’ and ‘Nw_Project’ will
# be created if they do not exist
# Initialising the leaf directory
dir = "pract"
# Parent Directories
prt_dir = "C:/Users/Shailendra/"
# Mode
m = 0o666
pth = path.join(prt_dir, dir )
# Create the directory named 'pract'
makedirs(pth, m)
print("The new directory named '% s' created" % dir )
Output:
The new directory named 'Shailendra' created
The new directory named 'pract' created
Listing out the Directories and Files with Python:
To get the list of all the directories and files present in the specified directory, we use the listdir( ) method in Python.If any directory is not specified by the user then all the directories and filed present in the current working directory will be returned.
Example to illustrate the listdir( ) method:
# Importing the OS module
from os import *
# Getting the list of all the directories and files
# present in the root directory
pth = "/"
dir_lst = listdir( pth )
print("The directories and files present in '", pth, "' are :")
# Returning the list
print(dir_lst)
Output:
The directories and files present in ' / ' are :
[' project', '$Recycle.Bin', '$SysReset', '$WINDOWS.~BT', '$WinREAgent', '.GamingRoot', 'Apps', 'DELL', 'dell.sdr', 'Documents and Settings', 'Drivers', 'DumpStack.log.tmp', 'FIOD.manifest', 'hiberfil.sys', 'Intel', 'OneDriveTemp', 'pagefile.sys', 'PerfLogs', 'Program Files', 'Program Files (x86)', 'ProgramData', 'Recovery', 'swapfile.sys', 'System Volume Information', 'Users', 'Windows', 'XboxGames']
Deleting Files or Directories using Python:
To delete Files and Directories, multiple methods are provided by the OS module. They are as follows:
- The remove( ) method
- The rmdir( ) method
Using the remove( ) method to delete files or directories:
When we want to delete or remove a file path, the remove( ) method is used. This method is not able to delete or remove a directory. The “OS Error” is raised by this method if the specified path is a directory.
Example to illustrate this method:
# Importing the OS module
from os import *
# Name of the file
f = 'file1.txt'
# Location of the file
loc = " D:/Practice Projects/java T point/"
# Path
pth = path.join( loc, f )
# Removing the specified file
# 'file1.txt'
remove( pth )
Using the rmdir( ) method to delete files or directories:
If we want to delete or remove an empty directory, we use the rmdir( ) method. If the specified path is not an empty directory, then this method raises an “OS Error”.
Example to illustrate this method:
# Importing the OS module
from os import *
# Name of the directory
dir = "java T point"
# The name of the parent Directory
prt = " D:/Practice Projects/"
# Path
pth = path.join( prt, dir )
# Removing the Directory
# "java T point"
rmdir( pth )
Commonly Used Functions:
- os.name( ) -> This function is used to give the name of the imported module that depends on the operating system. Currently, the following names have been registered: ‘nt’, ‘os2’, ‘java’, ‘posix’, and ‘riscos’.
from os import *
print(name)
Output:
nt
Note: The output may differ for different interpreters.
- os.error -> This error is raised by all the functions when inaccessible or invalid file paths and names are passed, or any other arguments having the correct type but the operating system does not accept them. It is a kind of nickname given to the built-in OSError exception.
from os import *
try:
# If given file does not exist, then an IOError is thrown by the
# interpreter
fname = 'JTP.txt'
file = open( fname, 'r' )
data = file.read()
file.close()
# If IOError is thrown by any of the above lines,
# the control directly jumps to this part
except IOError:
# print(os.error) will <class 'OSError'>
print('Problem reading: ' + fname)
Output:
Traceback (most recent call last):
File "C:\Users\Shailendra\calculator.py", line 7, in <module>
file = open( fname, 'r+' )
TypeError: 'str' object cannot be interpreted as an integer
Note: In the above-given example, in any of the cases, the code will continue with the portion coded after the try/except part.
- os.popen( ) -> This method is used to open a pipe from or to a command. The returned value depends on the mode, i.e., ‘r’ or ‘w’.
The syntax for this method:
os.popen( command [, mode [, buffsize ] ] )
In this syntax, it is not necessary to provide arguments for mode and buffsize, default ‘r’ is taken as mode if arguments are not provided.
from os import *
fname = "JTP.txt"
# popen() is similar to open()
f = open( fname, 'r')
f.write( " Hi " )
f.close()
f = open(fname, 'w')
data = f.read()
print( data )
# popen() provides a pipe/gateway and accesses the file directly
f = popen(fname, 'w')
f.write(" Hi " )
# File not closed, shown in next function.
Output:
Hi
Note: No output is shown for popen( ), this method directly makes changes in the file.
- os.close( ) -> This method is used to close the file descriptor ‘fname’. To close the file opened using the open( ) method, only the close( ) method can be used, but if the file is opened using the popen( ) method then it can be closed using either the os.close( ) method or the close( ) method. The TypeError is thrown if the file is opened using the open( ) method is being closed using the os.close( ) method.
import os
fname = "JTP.txt"
f = open(fname, 'r')
data = f.read( )
print( data )
os.close( f )
- os.rename( ) -> This method is used to change the name of the pre-existing file, and that file should have sufficient permissions to change its name.
# Importing the OS module.
from os import *
fname = "JTP.txt"
rename(fname, 'jtp.txt')
rename(fname, 'ttp.txt')
Output:
Traceback (most recent call last):
File "C:\Users\Shailendra\calculator.py", line 5, in <module>
rename(fname, 'jtp.txt')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'JTP.txt' -> 'jtp.txt'
(Note: This error is shown because when the function is executed the first time, it changes the name of the file, and therefore when the function is made run again it is not able to find the file with the name passed as an argument, hence the FileNotFoundError shows up.)
- os.remove( ) -> Whenever we want to remove/delete any file present in our system, the os.remove( ) method is used. To remove the required file, its name has to be passed to this method as an argument.
# Importing the OS module.
from os import *
# Removing the required file
remove("JTP.txt")
A layer of abstraction between the user and the operating system is provided by the OS module. If we try to remove a non-existing file, then the FileNotFoundError is thrown.
- os.path.exists( ) -> To check the existence of any file, we use this method and pass the name of the file as the argument to this method. The PATH is a sub-module that lies in the OS module, which is used to perform multiple functions.
# Importing the OS module.
from os import *
# Passing the name of the file as the argument
rslt = path.exists("name_of_the_file")
print( rslt )
Output:
False
- os.path.getsize( ) -> To get the size of any particular file this method is used. In this method, the name of the file is passed as an argument/parameter.
Example to illustrate this method:
# Importing the OS module.
import os
s = os.path.getsize( "name_od_the_file" )
print("The size of the file is", s, " bytes.")
Output:
The size of the file is 192 bytes.