Programs often need to persist data between runs. Files provide permanent storage on disk. File handling covers opening, reading, writing, appending, and closing files. In Python, the open() function is used with a mode specifying how to interact with the file.
| Mode | Description | File must exist? |
|---|---|---|
'r' | Read — read from start of file | Yes — FileNotFoundError if not |
'w' | Write — overwrite entire file (or create if absent) | No — creates new file |
'a' | Append — add to end of file | No — creates if absent |
'r+' | Read and write | Yes |
'b' | Binary mode (combine: 'rb', 'wb') | Depends on base mode |
# Method 1: read entire file as a string
with open('data.txt', 'r') as f:
content = f.read()
# Method 2: read line by line
with open('data.txt', 'r') as f:
for line in f:
print(line.strip()) # strip removes trailing newline
# Method 3: read all lines into a list
with open('data.txt', 'r') as f:
lines = f.readlines() # list of strings, each ending in \n
# Write (overwrites existing content)
with open('output.txt', 'w') as f:
f.write("Hello, World!\n")
f.write("Second line\n")
# Append (adds to end, preserves existing content)
with open('log.txt', 'a') as f:
f.write("New log entry\n")
The with statement (context manager) automatically closes the file when the block exits, even if an exception is raised. This prevents resource leaks — a file left open consumes a file handle (OS resource). Always use with open(...) instead of f = open(...) with a separate f.close().
CSV (Comma-Separated Values) files store tabular data. Python's csv module handles them correctly (dealing with commas inside quoted fields, newlines, etc.)
import csv
# Reading CSV
with open('students.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row) # each row is a list
# Writing CSV
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Grade'])
writer.writerow(['Alice', 'A'])
An exception is an error that occurs at runtime, interrupting normal program flow. Without handling, exceptions cause the program to crash. Exception handling allows a program to detect errors, respond to them gracefully, and continue running where appropriate.
try:
# Code that might raise an exception
number = int(input("Enter a number: "))
result = 100 / number
except ValueError:
# Handle specific exception type
print("Not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
# Catch any remaining exception
print(f"Unexpected error: {e}")
else:
# Runs only if no exception was raised
print(f"Result: {result}")
finally:
# Always runs — even if exception occurred
print("Done.")
| Exception | Cause |
|---|---|
| ValueError | Argument of wrong value (e.g. int("abc")) |
| TypeError | Wrong type (e.g. "5" + 5) |
| ZeroDivisionError | Division by zero |
| FileNotFoundError | File does not exist |
| IndexError | List index out of range |
| KeyError | Dictionary key not found |
| NameError | Variable not defined |
| OverflowError | Result too large to represent |
Code can raise (throw) its own exceptions using the raise keyword. This is useful for enforcing preconditions or signalling invalid states to the caller.
def set_age(age):
if age < 0 or age > 150:
raise ValueError(f"Invalid age: {age}")
return age
Create custom exception types by inheriting from Exception:
class InsufficientFundsError(Exception):
def __init__(self, amount):
super().__init__(f"Insufficient funds: need {amount} more")
self.amount = amount
# Using the custom exception
raise InsufficientFundsError(50)
try:
with open('data.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print("File not found — creating empty file")
with open('data.txt', 'w') as f:
f.write("")
except PermissionError:
print("Access denied — cannot read file")
with statement for file handling — it automatically closes the file and handles exceptions during I/O. For multiple exception types, list them in order from most specific to most general (catch ValueError before Exception).8 questions · 22 marks · instantly marked
| Term | Definition |
|---|