Part 4
File Handling & Modules
Files, CSV/JSON, Exceptions & Modules
1. Reading & Writing Files
with open("[Link]", "w") as f:
[Link]("Hello, Python!\n")
[Link]("File handling is easy.\n")
with open("[Link]", "r") as f:
content = [Link]()
print(content)
The with statement automatically closes the file, even if an error occurs.
2. Reading Line by Line
with open("[Link]", "r") as f:
for line in f:
print([Link]())
3. Working with CSV & JSON
import csv, json
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](["name", "age"])
[Link](["Alice", 25])
data = {"name": "Alice", "age": 25}
with open("[Link]", "w") as f:
[Link](data, f)
4. Exception Handling
Use try/except to handle errors gracefully instead of crashing the program.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("That's not a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Result:", result)
finally:
print("Done.")
5. Modules & Packages
Modules let you organize and reuse code across files.
# [Link]
def add(a, b):
return a + b
# [Link]
import mymath
print([Link](3, 4)) # 7
from mymath import add
print(add(5, 6)) # 11
Commonly used standard-library modules:
• os — interact with the operating system
• datetime — work with dates and times
• random — generate random numbers
• math — mathematical functions
• re — regular expressions
6. Virtual Environments & pip
Virtual environments isolate a project's dependencies from other projects and the system Python
installation.
python -m venv venv
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
pip install requests
pip freeze > [Link]
pip install -r [Link]
7. Custom Exceptions
You can define your own exception classes by inheriting from Exception, which is useful for
signaling domain-specific errors.
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Not enough balance")
return balance - amount
try:
withdraw(100, 150)
except InsufficientFundsError as e:
print("Error:", e)
8. Working with Paths (pathlib)
The pathlib module offers an object-oriented, cross-platform way to handle file paths.
from pathlib import Path
p = Path("data") / "[Link]"
print([Link]())
print([Link]) # .txt
print([Link]) # report
print([Link]) # data
for file in Path(".").glob("*.py"):
print(file)
9. Context Managers
The with statement works with any object that implements __enter__ and __exit__. You can
create your own:
class Timer:
def __enter__(self):
import time
[Link] = [Link]()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
import time
print(f"Elapsed: {[Link]() - [Link]:.4f}s")
with Timer():
total = sum(range(1000000))
10. Logging
The logging module is the standard way to record program events, more flexible than plain print
statements.
import logging
[Link](level=[Link])
[Link]("Program started")
[Link]("Low disk space")
[Link]("Failed to connect to database")
11. Creating & Publishing Packages
A package is simply a directory containing an __init__.py file along with related modules:
mypackage/
__init__.py
[Link]
[Link]
# usage
from mypackage import utils
from [Link] import User
Practice Exercises
• Write a program that reads a text file and counts the number of words in it.
• Write a function that safely divides two numbers and handles exceptions.
• Create a small module with utility functions and import it into another script.
• Write a program that logs every step of a simple task using the logging module.
• Create a custom exception for an 'invalid age' scenario in a registration form.
• Use pathlib to list all .txt files in a folder and print their sizes.
• Build a context manager that opens and automatically closes a database connection.