OS Module in python with examples

The os module in python provides functions for interacting with the operating system. OS comes under python’s  standard utility modules.This module provides a portable way of using operating system.

PYTHON OS MODULES FUNCTIONS-

Some important functions: 1.Handling the current working Directory

2.Creating a directory

3.Listing out files and directories with python

4.Deleting directory or files using python

1. HANDLING THE CURRENT WORKING DIRECTORY

To get the location of the current working directory os.getcwd().is used.

Example:This code uses the ‘os’ module to get and print the current working directory(CWD)of the python script.it retrieves the CWD using the ‘os.getcwd()’ and then prints it to the console.

2. CREATING A DIRECTORY

There are different methods avaliable in the OS module for creating a directory.These are-

os.mkdir()

os.makedirs()

os.mkdir(): By using os.mkdir() method in python is used to create a directory named path with the specified numeric mode.

Example:This code creates two directories:

1.The first directory is created using the os.mkdir() method without specifying the mode.

2.The second directory is created using the same method,but a specific mode(0o666)is provided,which grants read and write permissions.

os.makedirs(): os.makedirs()method in python is used to create a directory recursively.

Example:this code creates two directories.

3. LISTING OUT FILES AND DIRECTORIES WITH PYTHON

There is os.listdir().method in python is used to get the list of all files and directories in the specified directory.if we dont specify any directory,then the list of files and directories in the current working directory will be returned.

Example:This code lists all the files and directories in the root directory(“/”).It uses the os.listdir function to get the list of files and directories in the specified path and then prints the results.

4.DELETING DIRECTORY OR FILES USING PYTHON

OS modules provides different methods for removing directories and files in python.these are-

-using os.remove()

-using os.rmdir()

import os

searchdir = '.'

x = os.listdir('C:\new\review')
x = os.listdir('/users/david')
print(x)

 

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top