×

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

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

Cross Validation in Sklearn

Data scientists can benefit from cross-validation in machine learning in two key ways: it can assist in minimising the amount of data needed and ensure the artificial intelligence model is...

14 minutes read.

Accessing Key-value in Dictionary in Python

A Python word reference is an assortment of key-esteem matches where each key is related to worth. Worth in the key-esteem pair can be a number, a string, a rundown,...

5 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Python Statistical Module

Python Statistical Module The Python statistical module provides various functions that we can use in our Python program, to perform mathematical statistics operations on the numerical data given to us. The...

8 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.

Best app for python

What is python? Python is a prevalent, general-purpose, and high-level programming language. Python Programming Language is appropriate for experienced programmers and also for beginners. Python programming language is being utilized by...

19 minutes read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

Python Program for Linear Search

Introduction We employ specific algorithms to efficiently carry out our responsibilities, such as searching for an element in a given data structure. These algorithms fall under the category of searching algorithms....

4 minutes read.

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

Python Typing Module

An Introduction to the Typing Module The typing module is introduced in Python version 3.5 and used to provide hinting method types in order to support static type checkers and linters...

10 minutes read.

Working with CSV files in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

7 minutes read.

Python isinstance() function

Python isinstance() function The isinstance() function in Python returns a Boolean value ‘True’ if the given object is of the specified type, otherwise it returns False. Syntax isinstance(object, classinfo) Parameter object: It is a required parameter which represents an object. classinfo: This...

1 minute read.

Comment starts with the symbol in Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Virtual Environment

In this tutorial, we will understand Virtual Environment in Python. We will understand the need for a virtual environment and also see how to make use of it in python....

3 minutes read.