Discuss the following methods of OS module

7. Discuss the following methods of OS module
i) chdir()
ii) rmdir()
iii) walk()
iv) list dire()

Answer:

OS Module Methods

The os module provides functions to interact with the operating system, especially for handling files and directories.


i) os.chdir(path)

Purpose: Changes the current working directory to the specified path.

import os
os.chdir('C:\\Users\\Mithun\\Documents')

ii) os.rmdir(path)

Purpose: Removes an empty directory.

os.rmdir('old_folder')

iii) os.walk(path)

Purpose: Walks through a directory tree (i.e., all folders and files inside a directory).

for foldername, subfolders, filenames in os.walk('.'):
    print('Folder:', foldername)
    print('Files:', filenames)

iv) os.listdir(path)

Purpose: Lists all files and directories in the given path.

print(os.listdir('.'))

Leave a Reply

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