PANIMALAR ENGINEERING COLLEGE
(An Autonomous Institution, Affiliated to Anna University, Chennai)
ANSWER KEY
Name of the Course PROGRAMMING IN PYTHON
Course Code 23ES1206
Regulation 2023
Semester II
UNIT – IV
FILES AND EXCEPTION HANDLING
PART A – 2 MARKS
Q1. [2 Marks] Define a file and give its advantages.
Answer:
A file is a named collection of data stored permanently on a storage device. Advantages:
• Permanent storage of data beyond program execution.
• Large data can be stored and retrieved efficiently.
• Data sharing between multiple programs.
• Supports sequential and random access.
Q2. [2 Marks] List the different file modes used in Python.
Answer:
• 'r' – Read (default). File must exist.
• 'w' – Write. Creates or overwrites file.
• 'a' – Append. Adds to end of file.
• 'x' – Exclusive creation. Fails if file exists.
• 'rb', 'wb' – Read/Write in binary mode.
• 'r+' – Read and write.
Q3. [2 Marks] Write the syntax to open a file in Python.
Answer:
# Basic syntax
file_object = open('[Link]', 'mode')
# Recommended (auto-closes file)
with open('[Link]', 'r') as f:
content = [Link]()
Q4. [2 Marks] Describe the role and applications of command line arguments in Python programs.
Answer:
Command-line arguments allow users to pass inputs to a Python script at runtime. Accessed via [Link].
import sys
# python [Link] arg1 arg2
print([Link][0]) # script name
print([Link][1]) # first argument
Applications: processing files specified at runtime, configuring program behaviour, batch processing.
Q5. [2 Marks] Define tell() and seek() method in file handling.
Answer:
tell(): Returns the current position (byte offset) of the file pointer.
seek(offset, whence): Moves the file pointer to a specific position. whence: 0=start, 1=current, 2=end.
f = open('[Link]', 'r')
print([Link]()) # 0 (start)
[Link](5)
print([Link]()) # 5
[Link](0) # back to start
Q6. [2 Marks] Write the difference between append and write mode.
Answer:
Write mode ('w'): Opens file for writing. If file exists, its contents are erased (overwritten). If file doesn't exist, a
new file is created.
Append mode ('a'): Opens file for writing. New data is added at the end without erasing existing content.
Creates file if it doesn't exist.
Q7. [2 Marks] List and explain any two built-in exceptions.
Answer:
• ValueError – Raised when a function receives an argument of correct type but invalid value. Example:
int('abc')
• ZeroDivisionError – Raised when a number is divided by zero. Example: 10/0
• IndexError – Raised when sequence index is out of range.
Q8. [2 Marks] Why are clean-up actions important in exception handling, and how are they implemented.
Answer:
Clean-up actions ensure resources (files, connections) are properly released even if an exception occurs.
Implemented using the finally block, which always executes regardless of exception.
try:
f = open('[Link]')
# process
except FileNotFoundError:
print('File not found')
finally:
[Link]() # always runs
Q9. [2 Marks] How can a user-defined exception be defined in Python?
Answer:
User-defined exceptions are created by inheriting from the built-in Exception class (or any of its subclasses).
class MyError(Exception):
pass
try:
raise MyError('Custom error message')
except MyError as e:
print('Caught:', e)
Q10. [2 Marks] What is exception chaining in Python? Provide an example.
Answer:
Exception chaining allows linking one exception to another using raise ... from ... syntax to show the original
cause.
try:
int('abc')
except ValueError as e:
raise TypeError('Conversion failed') from e
PART B – 13 MARKS
Q1. [7+6 Marks] i) Copy file 50 chars at a time ii) Count words in file
Answer:
i) Copy file (50 characters at a time):
def copy_file(src, dest):
try:
with open(src, 'r') as f1, open(dest, 'w') as f2:
while True:
chunk = [Link](50)
if not chunk:
break
[Link](chunk)
print('File copied successfully.')
except FileNotFoundError:
print(f'Source file not found: {src}')
copy_file('[Link]', '[Link]')
ii) Count words in a file:
def count_words(filename):
try:
word_count = 0
with open(filename, 'r') as f:
for line in f:
words = [Link]()
word_count += len(words)
print(f'Total words in file: {word_count}')
except FileNotFoundError:
print('File not found.')
count_words('[Link]')
Q2. [13 Marks] Explain tell() and seek() methods with examples
Answer:
tell(): Returns the current byte position of the file pointer.
seek(offset, whence): Moves the file pointer.
• whence=0: from beginning (default)
• whence=1: from current position
• whence=2: from end of file
# Create a sample file
with open('[Link]', 'w') as f:
[Link]('Hello World Python')
with open('[Link]', 'r') as f:
print('Initial position:', [Link]()) # 0
print([Link](5)) # Hello
print('After reading 5:', [Link]()) # 5
[Link](6) # Move to position 6
print('After seek(6):', [Link]()) # 6
print([Link](5)) # World
[Link](0) # Back to start
print('After seek(0):', [Link]()) # 0
print([Link]()) # Hello World Python
[Link](0, 2) # Move to end
print('File size:', [Link]()) # 18
Q3. [7+6 Marks] i) IndexError handling ii) ValueError handling
Answer:
i) IndexError handling:
def access_element():
lst = [10, 20, 30, 40, 50]
print('List:', lst)
try:
index = int(input('Enter index to access: '))
print(f'Element at index {index}:', lst[index])
except IndexError:
print(f'IndexError: Index out of range! List has {len(lst)} elements (0 to
{len(lst)-1}).')
except ValueError:
print('Please enter a valid integer index.')
access_element()
ii) ValueError handling:
def safe_addition():
try:
a = float(input('Enter first number: '))
b = float(input('Enter second number: '))
print(f'Sum = {a + b}')
except ValueError:
print('ValueError: Please enter numeric values only.')
safe_addition()
Q4. [13 Marks] Differentiate syntax errors and exceptions
Answer:
Syntax Errors: Detected by Python interpreter before execution. The program does not run at all.
Example:
# SyntaxError examples
if True # Missing colon
print('hi')
def func) # Missing opening parenthesis
Exceptions (Runtime Errors): Occur during program execution even if syntax is correct.
Example:
# These are syntactically correct but raise exceptions at runtime
a = int('abc') # ValueError
print(10 / 0) # ZeroDivisionError
lst = [1,2,3]
print(lst[10]) # IndexError
print(x) # NameError (x not defined)
Key differences:
• Syntax error: detected at compile/parse time. Exception: detected at runtime.
• Syntax error: program cannot start. Exception: program runs until the error.
• Syntax error: cannot be caught with try-except. Exceptions can be caught.
• Syntax error: always fatal. Exceptions can be handled gracefully.
Q5. [7+6 Marks] i) try, except, finally ii) FileNotFoundError
Answer:
i) try-except-finally:
• try block: contains code that might raise an exception.
• except block: handles the exception if it occurs.
• else block (optional): runs if no exception in try block.
• finally block: always executes, used for cleanup.
try:
x = int(input('Enter a number: '))
result = 100 / x
except ValueError:
print('Please enter a valid integer.')
except ZeroDivisionError:
print('Cannot divide by zero!')
else:
print(f'Result: {result}')
finally:
print('Program ended.')
ii) FileNotFoundError handling:
try:
filename = input('Enter filename: ')
with open(filename, 'r') as f:
content = [Link]()
print('File contents:')
print(content)
except FileNotFoundError:
print(f'Error: The file does not exist.')
except PermissionError:
print('Error: No permission to read the file.')
finally:
print('File operation complete.')
Q6. [7+6 Marks] i) Raising exceptions ii) TypeError for non-numeric input
Answer:
i) Raising exceptions: Python allows explicitly raising exceptions using the raise keyword.
def validate_age(age):
if age < 0:
raise ValueError('Age cannot be negative')
if age > 150:
raise ValueError('Age seems unrealistic')
return f'Valid age: {age}'
try:
print(validate_age(-5))
except ValueError as e:
print('ValueError:', e)
ii) Raise TypeError for non-numeric values:
def add_numbers(a, b):
if not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
raise TypeError('Both arguments must be numeric')
return a + b
try:
x = input('Enter first value: ')
y = input('Enter second value: ')
# Try to convert; if fails, it's non-numeric
x = float(x)
y = float(y)
print('Sum:', add_numbers(x, y))
except ValueError:
raise TypeError(f'Non-numeric value entered') from None
except TypeError as e:
print('TypeError:', e)
Q7. [13 Marks] File operations with examples
Answer:
Python provides various file operations through the built-in open() function.
# 1. Write to a file
with open('[Link]', 'w') as f:
[Link]('Alice 85\n')
[Link]('Bob 72\n')
[Link]('Charlie 91\n')
print('File written successfully')
# 2. Read entire file
with open('[Link]', 'r') as f:
content = [Link]()
print('Full content:')
print(content)
# 3. Read line by line
with open('[Link]', 'r') as f:
print('Line by line:')
for line in f:
print([Link]())
# 4. Read all lines into list
with open('[Link]', 'r') as f:
lines = [Link]()
print('Total lines:', len(lines))
# 5. Append to file
with open('[Link]', 'a') as f:
[Link]('Diana 78\n')
print('Appended successfully')
PART C – 15 MARKS
Q1. [15 Marks] File processing: different modes, tell/seek, word and line count
Answer:
def count_words_lines(filename):
word_count = 0
line_count = 0
with open(filename, 'r') as f:
for line in f:
line_count += 1
words = [Link]()
word_count += len(words)
return word_count, line_count
# Create sample file
with open('[Link]', 'w') as f:
[Link]('Hello World\n')
[Link]('Python is awesome\n')
[Link]('File handling is easy\n')
# Different modes demo
print('=== Read Mode ===')
with open('[Link]', 'r') as f:
print('Initial tell():', [Link]())
print('First 5 chars:', [Link](5))
print('After read(5), tell():', [Link]())
[Link](0)
print('After seek(0), tell():', [Link]())
print('Full content:')
print([Link]())
# Word and line count (without built-in count functions)
words, lines = count_words_lines('[Link]')
print(f'\nWord Count: {words}')
print(f'Line Count: {lines}')
Q2. [15 Marks] Evaluate and fix the file-copying code
Answer:
i) Errors in the given code:
• f1 = open(src) — No mode specified (minor; defaults to 'r', but should be explicit).
• [Link] and [Link] — Missing parentheses; these are references, not calls. Files are NOT closed.
• print([Link]()) — Called after reading; fine in itself, but context may cause issues.
• No exception handling — if src doesn't exist, program crashes.
ii) Corrected version with exception handling and with block:
src = '[Link]'
dest = '[Link]'
try:
with open(src, 'r') as f1, open(dest, 'w') as f2:
for line in f1:
[Link](line)
print('Position after reading:', [Link]())
[Link](5)
print('Position after seek(5):', [Link]())
print('File copied successfully.')
except FileNotFoundError:
print(f'Error: Source file "{src}" not found.')
except PermissionError:
print('Error: Permission denied.')
except IOError as e:
print(f'I/O error: {e}')
The with block ensures files are automatically closed after the block exits, even if an exception occurs.
Q3. [15 Marks] User-defined exception: invalid marks
Answer:
# a) Custom exception class
class InvalidMarksError(Exception):
def __init__(self, marks, message='Marks must be between 0 and 100'):
[Link] = marks
[Link] = message
super().__init__([Link])
def __str__(self):
return f'InvalidMarksError: {[Link]} (Got: {[Link]})'
# b) Function to accept and validate marks
def get_marks(subject):
try:
marks = float(input(f'Enter marks for {subject}: '))
# c) Raise exception if out of range
if marks < 0 or marks > 100:
raise InvalidMarksError(marks)
return marks
except ValueError:
print('Please enter a numeric value.')
return 0
except InvalidMarksError as e:
print(e)
return 0
subjects = ['Maths', 'Physics', 'Chemistry', 'English', 'Python']
total = 0
print('=== Student Marks Entry ===')
for sub in subjects:
m = get_marks(sub)
total += m
print(f'\nTotal: {total}/500')
print(f'Average: {total/len(subjects):.2f}')