Chapter 6(12 Marks)
2 Marks
1.List four file modes in python
Ans:
•r
• rb
• r+
• rb+
•w
• wb
• w+
• wb+
•a
• ab
• a+
• ab+
2. Explain open() and close() methods for opening and closing a file.
Ans:
open():The open() function is used to open a file and returns a file object.
close():The close() method of a file object flushes any unwritten information and closes the file
object.
3.Write use of try:finally block with Syntax.
Ans:
Use: The finally block, if specified, will be executed regardless if the try block raises an error or not.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
4. Describe print() functions with example.
Ans:
Use:
The print() function is used to display output to the console or standard output device.
Example:
print("Hello, World!")
print("apple", "banana", "orange", sep=", ")
5. Give the syntax and significance of input() method.
Ans:
Use: The input() method in Python is used to read input from the user through the console or
command line.
Syntax:
variable_name = input(prompt)
6.State the use of read() and readline() function in python file handling mechanism.
Ans:
read(): The read() function is used to read the entire content of a file as a string.
readline():The readline() function reads a single line from the file.
7. State the use of write() and writeline() function in python file handling mechanism.
Ans.
write():The write() function is used to write a string to a file.
writeline():The writelines() function is used to write a sequence of strings to a file.
4 Marks
1. Explain with an example, how to rename or delete File or Directory.
Ans:
Renaming File:
For renaming file in Python, the rename() method is used. For that purpose, it is required to import the
module
Example:
import os
os.rename(r'd:\test1.txt',1'D:\test2.txt')
print("File is renamed")
Deleting File
For removing the file, we use remove method belonging
to the os module.
Example:
import os
os.rename('d:\test1.txt')
print("File is removed")
2. Explain exception handling with example using try, except, raise keywords.
Ans:
An exception is an event, which occurs during the execution of program that disrupts the normal
flow of the program.
In general, when python script encounters situation that it cannot cope with, it raises an exception.
Example:
try:
x = int(input("Enter a number: "))
if x == 0:
raise ValueError("Zero is not allowed")
result = 10 / x
print("Result:", result)
except ValueError as ve:
print("ValueError occurred:", ve)
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print("An error occurred:", e)
else:
print("No exceptions occurred")
finally:
print("Finally block executed")
3. Explain how to create a user defined exception with an example.
Ans:
Although standard exceptions in Python provide adequate functionality, It is advantageous to
create user defined exception.
With user defined exception, one can add the desired information to the exception handlers.
Example:
class NegativeNumberError(Exception):
def __init__(self, message="Number cannot be negative"):
self.message = message
super().__init__(self.message)
def process_number(num):
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed")
else:
print("Number processed successfully")
try:
num = int(input("Enter a number: "))
process_number(num)
except NegativeNumberError as e:
print("Error:", e)
4. Write a python program which will throw exception if the value entered by user is less than
zero.
Ans.
class NegativeNumberError(Exception):
def __init__(self, message="Number cannot be negative"):
self.message = message
super().__init__(self.message)
def process_number(num):
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed")
else:
print("Number processed successfully")
try:
num = int(input("Enter a number: "))
process_number(num)
except NegativeNumberError as e:
print("Error:", e)
5. Write a python program to read contents of first.txt file and write same content in second.txt
file.
Ans:
try:
with open("first.txt", "r") as first_file:
content = first_file.read()
with open("second.txt", "w") as second_file:
second_file.write(content)
print("Content copied from 'first.txt' to 'second.txt' successfully.")
except FileNotFoundError:
print("Error: One or both files not found.")
except IOError:
print("Error: Unable to read from or write to the file.")
except Exception as e:
print("An error occurred:", e)
6. Explain seek() and tell() functions for file pointer manipulation.
Ans
i. seek():
The seek() function is used to move the file pointer to a specific position within the file.
It takes two arguments: the offset and the optional whence parameter.
Syntax:
file_object.seek(offset, whence)
ii. tell():
The tell() function returns the current position of the file pointer within the file.
It returns an integer representing the byte offset from the beginning of the file.
Syntax:
file_object.tell()
7. Explain following python functions:
Ans.
i. getcwd():This function returns a string representing the current working directory of the Python
process.
ii. mkdir():It is used to create a new directory (folder) with the specified name.
iii. chdir():It is used to change the current working directory to the one specified.
iv. listdir():It is used to list all the files and directories in the specified directory.
8. Write a program to open a file in write mode and append some contents at the end of file.
Ans.
with open("example.txt", "a+") as file:
file.write("\nThis content is appended at the end of the file.")
print("Content has been appended to the file.")