UNIT- IV- FILES AND EXCEPTION HANDLING
PART A ( 2 Marks)
1. Define a file and give its advantages.
➔ A file is a named location on storage media to store data permanently.
Advantages:
Stores large amounts of data permanently.
Easy to access and modify anytime.
2. Differentiate text file and binary file.
Text File Binary File
Stores data as readable characters. Stores data in binary (0s and 1s).
Can be opened and read easily in text editors. Needs special programs to read and edit.
3. Write the difference between ftell() and fseek().
ftell(): Returns the current file pointer position.
fseek(): Moves the file pointer to a specified location.
4. What is command line argument? Give its purposes.
➔ Arguments passed to a Python script while running it from the command line.
Purpose:
Provides input without hardcoding.
Automates and controls script execution.
5. Name the different modes used in file handling.
➔ Modes are:
'r' (read)
'w' (write)
'a' (append)
'b' (binary)
'+' (read and write)
6. List down some inbuilt exception.
➔ Examples:
ZeroDivisionError
IndexError
TypeError
ValueError
FileNotFoundError
7. What are the distinctions between append and write modes?
Write ('w') mode: Overwrites the file if it exists.
Append ('a') mode: Adds data at the end of the file without deleting existing content.
8. What is exception chaining in python? Provide an example.
➔ Exception chaining links one exception to another using raise ... from ....
Example:
try:
x=1/0
except ZeroDivisionError as e:
raise ValueError("Invalid input") from e
,9. How do you define a user-defined exception in Python? Write a basic example.
➔ Create a class inheriting from Exception.
Example:
class MyError(Exception):
pass
raise MyError("This is a user-defined error")
10. What is clean-up actions in exception handling? [BL4] [CO4] [2]
➔ Clean-up actions are tasks performed to release resources (like closing files or database connections)
even if an error occurs.
Done using finally block.
Descriptive Questions ( 13 Marks)
1. How can you read and write data in a file using Python? provide source code
examples for both operations.
File Reading and Writing in Python
In Python, file operations like reading and writing are performed using built-in functions.
The important steps are:
1. Open the file (open() function)
2. Read/Write the file
3. Close the file (close() function)
The open() function syntax is:
open(filename, mode)
filename: Name of the file.
mode: Mode of opening ('r' - read, 'w' - write, 'a' - append, 'b' - binary etc.)
Writing Data to a File (Write Operation)
Source Code:
# Open a file in write mode
file = open("example.txt", "w")
# Write data into the file
file.write("Hello, this is my first file!\n")
file.write("Python makes file handling easy.\n")
# Close the file
file.close()
print("Data written successfully.")
Explanation:
open("example.txt", "w") → Opens (creates if not exist) a file in write mode.
write() → Writes string data to the file.
close() → Safely closes the file after writing.
Note: If example.txt already exists, it will overwrite the old content.
Reading Data from a File (Read Operation)
, Source Code:
# Open the file in read mode
file = open("example.txt", "r")
# Read entire content of the file
content = file.read()
# Print the content
print("The file content is:\n")
print(content)
# Close the file
file.close()
Explanation:
open("example.txt", "r") → Opens the file for reading.
read() → Reads the entire file data as a single string.
print() → Displays the data on the screen.
close() → Safely closes the file after reading.
Alternative: Using with Statement (Best Practice)
Python provides a better way using with which automatically closes the file:
Writing Example:
with open("example2.txt", "w") as file:
file.write("This is written using with statement.\n")
file.write("No need to manually close the file.")
Reading Example:
with open("example2.txt", "r") as file:
content = file.read()
print(content)
Advantages of with:
Automatically closes the file.
Cleaner and more readable code.
No need to explicitly call close().
2. What are the ftell() and fseek() methods in file handling? Explain with suitable
examples.
ftell() and fseek() Methods in File Handling
In Python, while working with file objects, sometimes you need to:
Find where you are currently reading/writing inside a file.
Move to a specific position inside the file.
This is where ftell() and fseek() functions come into play.
1. ftell() Method
➔ The ftell() method returns the current position of the file pointer (cursor) from the beginning of the file,
measured in bytes.
Syntax:
file_object.tell()
➔ tell() is the function we use in Python (equivalent of C's ftell()).
Example:
# Open a file in write mode
PART A ( 2 Marks)
1. Define a file and give its advantages.
➔ A file is a named location on storage media to store data permanently.
Advantages:
Stores large amounts of data permanently.
Easy to access and modify anytime.
2. Differentiate text file and binary file.
Text File Binary File
Stores data as readable characters. Stores data in binary (0s and 1s).
Can be opened and read easily in text editors. Needs special programs to read and edit.
3. Write the difference between ftell() and fseek().
ftell(): Returns the current file pointer position.
fseek(): Moves the file pointer to a specified location.
4. What is command line argument? Give its purposes.
➔ Arguments passed to a Python script while running it from the command line.
Purpose:
Provides input without hardcoding.
Automates and controls script execution.
5. Name the different modes used in file handling.
➔ Modes are:
'r' (read)
'w' (write)
'a' (append)
'b' (binary)
'+' (read and write)
6. List down some inbuilt exception.
➔ Examples:
ZeroDivisionError
IndexError
TypeError
ValueError
FileNotFoundError
7. What are the distinctions between append and write modes?
Write ('w') mode: Overwrites the file if it exists.
Append ('a') mode: Adds data at the end of the file without deleting existing content.
8. What is exception chaining in python? Provide an example.
➔ Exception chaining links one exception to another using raise ... from ....
Example:
try:
x=1/0
except ZeroDivisionError as e:
raise ValueError("Invalid input") from e
,9. How do you define a user-defined exception in Python? Write a basic example.
➔ Create a class inheriting from Exception.
Example:
class MyError(Exception):
pass
raise MyError("This is a user-defined error")
10. What is clean-up actions in exception handling? [BL4] [CO4] [2]
➔ Clean-up actions are tasks performed to release resources (like closing files or database connections)
even if an error occurs.
Done using finally block.
Descriptive Questions ( 13 Marks)
1. How can you read and write data in a file using Python? provide source code
examples for both operations.
File Reading and Writing in Python
In Python, file operations like reading and writing are performed using built-in functions.
The important steps are:
1. Open the file (open() function)
2. Read/Write the file
3. Close the file (close() function)
The open() function syntax is:
open(filename, mode)
filename: Name of the file.
mode: Mode of opening ('r' - read, 'w' - write, 'a' - append, 'b' - binary etc.)
Writing Data to a File (Write Operation)
Source Code:
# Open a file in write mode
file = open("example.txt", "w")
# Write data into the file
file.write("Hello, this is my first file!\n")
file.write("Python makes file handling easy.\n")
# Close the file
file.close()
print("Data written successfully.")
Explanation:
open("example.txt", "w") → Opens (creates if not exist) a file in write mode.
write() → Writes string data to the file.
close() → Safely closes the file after writing.
Note: If example.txt already exists, it will overwrite the old content.
Reading Data from a File (Read Operation)
, Source Code:
# Open the file in read mode
file = open("example.txt", "r")
# Read entire content of the file
content = file.read()
# Print the content
print("The file content is:\n")
print(content)
# Close the file
file.close()
Explanation:
open("example.txt", "r") → Opens the file for reading.
read() → Reads the entire file data as a single string.
print() → Displays the data on the screen.
close() → Safely closes the file after reading.
Alternative: Using with Statement (Best Practice)
Python provides a better way using with which automatically closes the file:
Writing Example:
with open("example2.txt", "w") as file:
file.write("This is written using with statement.\n")
file.write("No need to manually close the file.")
Reading Example:
with open("example2.txt", "r") as file:
content = file.read()
print(content)
Advantages of with:
Automatically closes the file.
Cleaner and more readable code.
No need to explicitly call close().
2. What are the ftell() and fseek() methods in file handling? Explain with suitable
examples.
ftell() and fseek() Methods in File Handling
In Python, while working with file objects, sometimes you need to:
Find where you are currently reading/writing inside a file.
Move to a specific position inside the file.
This is where ftell() and fseek() functions come into play.
1. ftell() Method
➔ The ftell() method returns the current position of the file pointer (cursor) from the beginning of the file,
measured in bytes.
Syntax:
file_object.tell()
➔ tell() is the function we use in Python (equivalent of C's ftell()).
Example:
# Open a file in write mode