Unit 4
Unit 4
8 MARKS
33. Discuss various directory methods in OS module.
The OS module in Python provides a way to interact with the operating system, and one of
its key functionalities is managing directories. Here are various directory-related methods
provided by the os module:
1.os.mkdir(path[, mode])
Creates a new directory at the specified path.
Syntax:
os.mkdir(path, mode=0o777)
Creates a new directory at the specified path.
2. os.makedirs(path[, mode])
Creates intermediate directories in the path if they do not exist.
Syntax:
os.makedirs(path, mode=0o777)
3. os.rmdir(path)
Removes an empty directory.
Syntax:
os.rmdir(path)
4. os.removedirs(path)
Removes directories recursively, but only if they are empty.
Syntax:
os.removedirs(path)
5. os.listdir(path='.')
Returns a list of entries (files and directories) in the specified directory.
Syntax:
os.listdir(path='.')
6.os.chdir(path)
Changes the current working directory to the specified path.
Syntax:
os.chdir(path)
7. os.getcwd()
Returns the current working directory.
Syntax:
os.getcwd()
8. os.rename(src, dst)
Renames a file or directory from src to dst.
Syntax:
os.rename(src, dst)
9.os.path.isdir(path)
Checks if the given path is a directory.
Syntax:
os.path.isdir(path)
10.os.path.exists(path)
Checks if the specified path exists
Syntax:
os.path.exists(path)
34. Explain the utility of Assert and Raise keywords. Show how to handle
various exceptions with examples.
1. assert Keyword:
The assert keyword is used for debugging purposes in Python. It tests a
condition, and if the condition evaluates to False, it raises an AssertionError
exception with an optional message. It is mainly used to check if the code is
working as expected during development and testing.
Syntax:
assert condition, "Error message"
Example:
x = 10
assert x > 5, "x should be greater than 5"
assert x < 5, "x should be less than 5"
2. raise Keyword:
The raise keyword is used to manually raise exceptions in Python. You can use it to throw
exceptions when a certain condition is met in your code. It is commonly used for error
handling and custom exceptions.
Syntax:
raise ExceptionType("Error message")
Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18.")
else:
print("Age is valid.")
try:
age = int(input("Enter your age: "))
check_age(age)
except ValueError as e:
print(f"Error: {e}")
OUTPUT:
Enter your age: 20
Age is valid.
35. How can you create your own exceptions in Python? Write a program to
print the square root of a number, raise an exception if number is negative.
In Python, you can create your own exceptions by defining a custom exception class. This
class should inherit from the built-in Exception class (or one of its subclasses). You can then
use the raise keyword to raise your custom exception when needed.
Steps to Create Your Own Exception:
1. Define a Custom Exception Class: Inherit from the built-in Exception class.
2. Raise the Custom Exception: Use the raise keyword to throw the exception when a
specific condition is met.
Program to Print Square Root and Raise Exception for Negative Numbers:
import math
class NegativeNumberError(Exception):
def calculate_square_root(number):
if number < 0:
else:
return math.sqrt(number)
try:
result = calculate_square_root(num)
except NegativeNumberError as e:
print(f"Error: {e}")
except ValueError:
OUTPUT:
Enter a number: 16
The square root of 16.0 is 4.0