chapter 6 Question answers
chapter 6 Question answers
QUESTIONS 2 MARKS:-
Ans:-In Python, when working with files, you typically use file modes to specify the intention of how
you want to interact with the file. Here are four common file modes:
Read mode: Opens a file for reading. If the file does not exist, it raises an error.
Write mode: Opens a file for writing. If the file exists, it truncates the file to zero length;
otherwise, it creates a new file.
Append mode: Opens a file for appending. It creates the file if it does not exist. The data is
written at the end of the file without truncating the existing contents.
Binary mode: This mode is used when dealing with binary files like images, executables, etc. It
should be used in conjunction with other modes (e.g., 'rb' for reading a binary file, 'wb' for
writing a binary file).
2. Explain open() and close() methods for opening and closing a file?
Ans:-The open() method in Python is used to open a file and returns a file object. It takes two arguments
primarily: the file name/path and the mode in which the file is to be opened. After performing file
operations, it's essential to close the file to release the system resources it holds.
open():
close():
Description: The close() method is called on a file object to close the file once you're done with it.
Syntax: file_object.close()
Ans:-
The finally block will be executed no matter if the try block raises an error or not.
This can be useful to close objects and clean up resources.
The try:finally block in Python is used to ensure that certain actions are always performed,
regardless of whether an exception occurs or not.
Syntax:-
try:
finally:
Ans:-
The print() function in Python is used to display information to the console or terminal. It can output
strings, variables, or any expression that can be converted into a string format.
# Printing a string
print("Hello, World!")
# Printing multiple values
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
output:
Hello, World!
Ans:-
syntax :-input(prompt)
Significance:
User Input: The input() function is used to accept user input from the keyboard while a Python
program is running.
Prompting the User: The optional prompt parameter allows you to display a message or prompt
to the user, guiding them on what input is expected.
Returns a String: When the user enters some input followed by the Enter key, input() reads that
input as a string and returns it. If no input is provided and the user just presses Enter, it returns
an empty string ('').
Interactivity: input() makes Python programs interactive, allowing users to interact with the
program in real-time by providing input based on prompts or messages displayed by the
program.
6.State the use of read() and readline() function in python file handling mechanism.
Ans:-
read() Function:
Use: The read() function is used to read a specified number of bytes from the file, or if no size is
specified, it reads the entire contents of the file.
Syntax: file.read(size)
readline() Function:
Use: The readline() function is used to read a single line from the file each time it's called. It reads
characters from the current position of the file pointer until it encounters a newline character (\n) or
reaches the end of the file.
Syntax: file.readline()
7. State the use of write() and writeline() function in python file handling mechanism.
Ans:-
write() :
Use: The write() function is used to write data to a file. It allows you to write strings or binary data to a
file.
Syntax: file.write(str)
file: The file object that you want to write data to.
str: The string or binary data that you want to write to the file.
Writeline():
In Python, there is no built-in writeline() method. Instead we can use write() function to achieve
our results.
Questions-4marks
Ans:- Description: File manipulation operations such as renaming and deleting are common
tasks in programming, particularly when managing data or performing file system operations. In
Python, these operations can be accomplished using the os module, which provides functions
for interacting with the operating system. The os.rename() function allows you to change the
name of a file, while the os.remove() function is used to delete a file from the file system.
Program:-
import os
# Renaming a file
old_name = 'old_file.txt' # Specify the current name of the file
new_name = 'new_file.txt' # Specify the new name for the file
os.rename(old_name, new_name) # Rename the file
print(f"{old_name} has been renamed to {new_name}")
# Deleting a file
file_to_delete = 'file_to_delete.txt' # Specify the name of the file to delete
os.remove(file_to_delete) # Delete the file
print(f"{file_to_delete} has been deleted")
output:-
old_file.txt has been renamed to new_file.txt
file_to_delete.txt has been deleted
In this example, we demonstrate the process of renaming and deleting files using Python. First, we use
os.rename() to change the name of a file from 'old_file.txt' to 'new_file.txt'. Then, we
employ os.remove() to delete a file named 'file_to_delete.txt' from the file system. These
operations should be executed with caution, as renaming or deleting files can have permanent effects
on the file system and its contents. It's essential to ensure that the file names and paths provided are
accurate to avoid unintended modifications or deletions.
Explain exception handling with example using try, except, raise keywords.
(CO6)
Ans:-
Exception handling in Python allows you to gracefully handle errors or exceptional conditions
that may occur during the execution of your program. This helps prevent your program from
crashing and allows you to handle errors in a controlled manner.
The try block is used to enclose the code that may raise an exception. If an exception occurs within the
try block, Python looks for an except block to handle it. The except block specifies what to do when a
specific exception is raised.
Additionally, you can use the raise keyword to manually raise an exception when a specific condition is
met.
Program:- try:
# Attempt to open a file that doesn't exist
file = open('nonexistent_file.txt', 'r')
except FileNotFoundError:
print("File not found error occurred.")
except ZeroDivisionError:
print("Zero division error occurred.")
except IndexError:
print("Index error occurred.")
except Exception as e:
print("An unexpected error occurred:", str(e))
Output:-
File not found error occurred.
Zero division error occurred.
Index error occurred.
Explain how to create a user defined exception with an example. (CO6)(sample paper)
Ans:-
In most programming languages, including Python, you can create custom exceptions by subclassing
built-in exception classes. Here's a step-by-step guide on how to create a user-defined exception in
Python with an example:
Create a Base Exception Class: You can create a base exception class by subclassing Python's built-in
Exception class. This will serve as the foundation for your custom exceptions.
Define Your Custom Exception: Subclass the base exception class to create your custom exception. You
can add any additional attributes or methods specific to your exception if needed.
Raise Your Custom Exception: You can raise your custom exception whenever the desired condition is
met in your code.
def __str__(self):
return f'{self.__class__.__name__}: {self.message}'
# Example Usage
try:
num_apples = 15
buy_apples(num_apples)
except TooManyApplesError as e:
print(e)
In this example, CustomException is created as a base class inheriting from Python's built-in Exception
class.
TooManyApplesError is a custom exception class inheriting from CustomException. It defines an
initializer to set a custom error message.
The buy_apples() function raises TooManyApplesError if the number of apples exceeds the
maximum allowed limit.
In the example usage, buy_apples() is called with num_apples = 15, triggering the custom exception
to be raised, which is caught by the except block and the error message is printed.
This demonstrates the creation and usage of a user-defined exception in Python. You can extend this
pattern to create various custom exceptions tailored to your specific needs.
Write steps involved in creation of a user defined exception?(sample paper)
Ans:-
Creating a user-defined exception involves several steps:
Identify the Need: Determine where in your code you need to handle exceptional situations that
are not adequately covered by built-in exceptions. This could be situations specific to your
application's logic or requirements.
Create Your Custom Exception: Subclass the base exception class (if applicable) to create your
custom exception. Define the specific behavior, attributes, and methods of your exception.
Consider providing informative error messages or additional data to aid in debugging.
Implement Initialization: Implement an initialization method (__init__ in Python) for your custom
exception to customize its behavior. This method may accept parameters to initialize the exception
object with relevant data.
Raise Your Custom Exception: Within your code, identify the scenarios where your custom
exception should be raised. Use the raise statement followed by an instance of your custom
exception class to raise the exception when the specific condition is met.
Handle Your Custom Exception: Whenever your custom exception is raised, ensure that your code
has appropriate error handling mechanisms to catch and handle the exception. Use try and except
blocks to gracefully manage the exceptional situation, and consider providing meaningful feedback
to the user or logging the error for further analysis.
Test Your Custom Exception: Thoroughly test your custom exception by writing test cases that
cover both expected and unexpected scenarios. Verify that the exception is raised when it should
be, and ensure that it behaves as expected in different situations.
# Example Usage
try:
user_input = int(input("Enter a number greater than or equal to 10: "))
validate_input(user_input)
except ValueTooSmallError as e:
print(e.message)
except ValueError:
print("Invalid input. Please enter a valid integer.")
Output:-
Enter a number greater than or equal to 10: 5
The provided value 5 is too small. It should be greater than or equal to 10.
Program:-
class NegativeValueError(Exception):
pass
def get_positive_value():
value = float(input("Enter a positive value: "))
if value < 0:
raise NegativeValueError("Negative value entered!")
return value
try:
user_input = get_positive_value()
print("Entered value:", user_input)
except NegativeValueError as e:
print("Error:", e)
Output:-
OUTPUT:-
getcwd():-
In Python, getcwd() is a method from the os module that is used to get the current working directory.
current_directory = os.getcwd()
print(current_directory)
This code will print the current working directory of your Python script.
mkdir() :-
In Python, mkdir() is a method from the os module that is used to create a new directory. Here's its
syntax:
import os
directory_path = "/path/to/new/directory"
os.mkdir(directory_path)
chdir() :-
In Python, chdir() is a method from the os module that is used to change the current working directory.
import os
new_directory_path = "/path/to/new/directory"
os.chdir(new_directory_path)
This code will change the current working directory to the specified path.
listdir():-
In Python, listdir() is a method from the os module that is used to list all files and directories in a
specified directory.
Here's its syntax:
import os
directory_path = "/path/to/directory"
contents = os.listdir(directory_path)
This code will print a list containing the names of all files and directories in the specified directory
(directory_path). If path is not provided, it defaults to the current working directory.