UNIT IV – Modules, Packages & File Handling
1. Introduction to Modules
A module in Python is a file that contains Python definitions, statements, and functions. It helps in
organizing code into manageable sections, making it reusable and maintainable. Each module has its
own namespace.
# example_module.py def greet(name): print(f"Hello, {name}!")
2. Importing Modules
Modules can be imported using the import keyword. The from-import statement allows you to import
specific attributes or functions from a module. The as keyword lets you give an alias name to a module.
import math print([Link](16)) from math import pow print(pow(2, 3)) import math
as m print([Link])
3. Built-in Modules in Python
Python provides several built-in modules that make development easier. Common examples: - math: for
mathematical functions - random: for random number generation - datetime: for date and time
manipulation - os: for operating system interaction - sys: for system-level operations
import math print("Square root of 25:", [Link](25)) import datetime
print("Today:", [Link]())
4. Packages in Python
A package is a collection of modules organized in directories. A directory becomes a package when it
contains an __init__.py file. Packages allow hierarchical module organization and reuse.
Diagram – Package Structure
my_package/ ■■■ __init__.py ■■■ [Link] ■■■ [Link]
from my_package import module1 [Link]()
5. Creating and Using Packages
To create a package: 1. Create a directory. 2. Add an empty __init__.py file inside it. 3. Add modules
(Python files). Then, import modules using the package name.
6. Introduction to File Handling
File handling allows reading from and writing to files. Python provides built-in functions like open(),
read(), write(), and close() to manage file operations.
file = open("[Link]", "w") [Link]("CSJMU BCA Python Notes") [Link]()
7. File Modes in Python
| Mode | Description | |------|--------------| | r | Read only | | w | Write only (overwrites) | | a | Append mode |
| r+ | Read and write | | w+ | Write and read (overwrites) |
8. Reading Files
Files can be read using read(), readline(), or readlines() methods.
file = open("[Link]", "r") print([Link]()) [Link]()
9. Writing and Appending Files
The write() and writelines() methods write data into a file, while append mode (a) adds new content at
the end.
file = open("[Link]", "a") [Link]("\nNew line added.") [Link]()
10. Exception Handling in Python
Exceptions are runtime errors that can be handled using try-except blocks. Handling exceptions
prevents abrupt termination of programs.
try: a = int(input("Enter number: ")) print(10 / a) except ZeroDivisionError:
print("Division by zero not allowed!") finally: print("Execution complete.")
Diagram – Exception Handling Flow
Start → Try Block → (If Error?) → Except Block → Finally Block → End
11. Assertions in Python
Assertions are used to check logical conditions during runtime using the assert keyword. If the condition
fails, AssertionError is raised.
x = 10 assert x > 5, "x must be greater than 5"
12. Summary
This unit covered the concept of Modules (code reusability), Packages (structured modules), File
Handling (data persistence), and Exception Handling (runtime error management). These are essential
for building robust Python applications.