×

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:

OS Module in Python

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:

OS Module in Python

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.

Related Topics

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

Python String Methods

Python String Methods Python has a set of built-in string methods. The Python string methods are as follows: capitalize() The string.capitalize() method returns a copy of the string by converting the...

5 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

Python Operator Precedence

Before knowing about the operator precedence in Python, we have to know about the operators in Python. So let's have a look at it. According to one definition, the operator is...

3 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

Python min() function

Python min() function returns you the minimum value element in an iterable. We can also use this function to determine the smallest value among various arguments passed to this function. We...

4 minutes read.

Python program to print array element present at even position

Python program to print array element present at even position In this program, we'll see a Python program that prints the elements of an array that are in even positions. We...

1 minute read.

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

Cx_Oracle Python with Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

Python for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

Python issubclass() Function

Python issubclass() Function The issubclass() function in Python returns a boolean value ‘True’ if the given object is a subclass of classinfo, else it returns False. Syntax issubclass(class, classinfo) Parameter class: It is a required parameter which represents a tuple...

1 minute read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Python hex() function

Python hex() function The hex() function in Python  converts the specified number into a hexadecimal value. Syntax hex(x) Parameter x: The parameter represents an Integer value. Return This function Returns hexadecimal string. Example 1 # Python Program explaining # the hex() function print("The...

1 minute read.