CS 111 › Lesson 8 of 12

File I/O & Exception Handling

Lesson 8 · CS 111: Programming I — Python · OKSTEM College

File I/O

Python uses the built-in open() function to read and write files. Always use the with statement - it automatically closes the file even if an error occurs.

# Writing a file with open("data.txt", "w") as f: f.write("Hello, file! ") f.write("Second line ") # Reading a whole file with open("data.txt", "r") as f: content = f.read() # Reading line by line (memory-efficient for large files) with open("data.txt") as f: for line in f: print(line.strip()) # strip() removes trailing # Appending to existing file with open("data.txt", "a") as f: f.write("Appended line ")
ModeMeaning
"r"Read (default). FileNotFoundError if file missing.
"w"Write. Creates file; overwrites if exists.
"a"Append. Creates file if missing; adds to end.
"rb"/"wb"Binary mode for images, PDFs, etc.

Exception Handling

Exceptions are runtime errors. Instead of crashing, you can catch and handle them gracefully.

try: # code that might raise an exception result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") except (ValueError, TypeError) as e: print(f"Error: {e}") except Exception as e: print(f"Unexpected: {e}") else: print("No exception occurred") finally: print("Always runs") # cleanup code here

Common Exceptions to Know

ExceptionWhen it occurs
ValueErrorWrong type of value: int("hello")
TypeErrorWrong type: "hi" + 5
IndexErrorList index out of range: [1,2][5]
KeyErrorDict key missing: d["missing"]
FileNotFoundErrorFile doesn't exist: open("nope.txt")
ZeroDivisionErrorDivision by zero

Raising Your Own Exceptions

def set_age(age): if age < 0: raise ValueError(f"Age cannot be negative: {age}") return age try: set_age(-5) except ValueError as e: print(e) # Age cannot be negative: -5

Practice Problems

Problem 1 - Safe number input

Keep prompting the user until they enter a valid integer. Use a while loop with try/except.

while True: try: n = int(input("Enter an integer: ")) break # exit loop only on success except ValueError: print("That's not an integer. Try again.") print(f"You entered: {n}")

Problem 2 - Word count from a file

Read a text file and print the total number of words. Handle the case where the file doesn't exist.

try: with open("essay.txt") as f: words = f.read().split() print(f"Word count: {len(words)}") except FileNotFoundError: print("File not found. Check the filename.")

Knowledge Check

Why should you use with open(...) as f: instead of just f = open(...)?

with has no speed advantage.
Correct - it's a context manager.
open() works with both modes.
You can open multiple with a single with (comma-separated), but that's not the main reason.
Quick Recap

The performance difference is negligible. The benefit is automatic resource cleanup.

Quick Recap

open() in 'rb' mode reads binary. The with statement works with both text and binary files.

Quick Recap

The main benefit of with is automatic cleanup. The file is closed when the block exits, even on exception.

Which exception is raised by int('hello')?

TypeError is for wrong type operations like 'hi' + 5.
Correct - the string has the right type (str) but wrong value.
SyntaxError is a compile-time error, not runtime.
IndexError is for out-of-range list/string indexing.
Quick Recap

TypeError: operation applied to wrong type. int('hello') fails because 'hello' is not a valid integer string - that's ValueError.

Quick Recap

SyntaxError means the code isn't valid Python syntax. int('hello') is syntactically fine - it fails at runtime.

Quick Recap

IndexError: seq[i] where i is out of range. int('hello') is a ValueError.

The finally block runs:

That is what the else clause does.
finally runs even without exceptions.
Correct - use finally for cleanup.
finally is commonly used for cleanup (closing files, database connections).
Quick Recap

else runs if no exception. finally always runs regardless of exceptions.

Quick Recap

finally is unconditional. It runs after try (and except/else) whether or not an exception happened.

Quick Recap

finally is very common - it ensures cleanup code runs. If you open a resource, close it in finally.

File mode 'a' does what?

That is mode 'r'.
That is mode 'w'.
Correct - 'a' adds without destroying existing content.
Binary mode is 'rb' or 'wb'.
Quick Recap

'r' = read. 'w' = write (overwrite). 'a' = append to end.

Quick Recap

'w' creates a new file or overwrites an existing one. 'a' preserves existing content and adds to the end.

Quick Recap

Binary mode adds 'b': 'rb' for binary read, 'wb' for binary write. 'a' is text append mode.

Which catches any exception as variable e?

Bare except catches everything but doesn't bind the exception to a variable.
Correct - catches all standard exceptions and binds to e.
e is not a valid exception type.
as e goes on the except clause, not try.
Quick Recap

Bare except: catches all exceptions but gives no access to the exception object. Use 'except Exception as e' to access it.

Quick Recap

You must specify an exception class. 'except e:' would try to use e as the exception type, not as the variable name.

Quick Recap

Syntax: except ExceptionType as variable_name. The as clause names the variable that holds the exception.