University of Delhi Syllabus ยท Unit 5

File and Exception Handling

Reading and writing files; handling errors and exceptions

Learning Outcomes
  • Read from and write to files
  • Use libraries for file handling
  • Identify common errors and exceptions
  • Handle exceptions gracefully

File Handling

Files are opened with the open function using modes such as r, w and a, and the with statement ensures a file is closed automatically. Text and CSV data can be read and written line by line.

with open("data.txt", "w") as f: f.write("Hello file") with open("data.txt") as f: print(f.read())

Errors and Exceptions

Errors detected during execution raise exceptions such as ValueError, ZeroDivisionError and FileNotFoundError. They are handled with try, except, else and finally so the program does not crash.

try: x = int(input("Enter a number: ")) print(10 / x) except ValueError: print("Not a valid number") except ZeroDivisionError: print("Cannot divide by zero")

Working with Libraries

Standard library modules such as csv and os simplify reading structured files and interacting with the file system.

import csv with open("marks.csv") as f: for row in csv.reader(f): print(row)

Summary

This unit covered file handling through the with statement and libraries, and the handling of errors and exceptions to write robust programs.

Exercises

  • Write a program to read a text file and count the number of lines, words and characters.
  • Write a program that handles division by zero and invalid input using exceptions.
  • Write a program to write student records to a CSV file and read them back.