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 filewithopen("data.txt", "w") as f:
f.write("Hello, file!
")
f.write("Second line
")
# Reading a whole filewithopen("data.txt", "r") as f:
content = f.read()
# Reading line by line (memory-efficient for large files)withopen("data.txt") as f:
for line in f:
print(line.strip()) # strip() removes trailing
# Appending to existing filewithopen("data.txt", "a") as f:
f.write("Appended line
")
Mode
Meaning
"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 / 0except 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
Exception
When it occurs
ValueError
Wrong type of value: int("hello")
TypeError
Wrong type: "hi" + 5
IndexError
List index out of range: [1,2][5]
KeyError
Dict key missing: d["missing"]
FileNotFoundError
File doesn't exist: open("nope.txt")
ZeroDivisionError
Division by zero
Raising Your Own Exceptions
defset_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.
whileTrue:
try:
n = int(input("Enter an integer: "))
break# exit loop only on successexcept 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:
withopen("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.