Unit 4: Modules and Packages & File Handling
Modules and Packages in Python
A module is a file that contains Python code such as functions, variables, and classes, which can be reused in other programs.
Advantages of Modules
- Code reusability
- Easy maintenance
- Better organization
- Faster development
User-Defined Modules
A module created by the user.
Steps to Create and Use a Module
Step 1: Create a module
Step 2: Import module
Ways to Import a Module
| Import Style | Example |
|---|---|
| import module | import math |
| from module import name | from math import sqrt |
| alias | import math as m |
What is a Package?
A package is a collection of related modules stored in directories.
Standard Library Modules
Python provides a rich standard library to perform common tasks.
random Module
Used to generate random numbers.
| Function | Use |
|---|---|
| random() | Float between 0–1 |
| randint(a,b) | Integer between a and b |
| choice() | Random element |
NumPy Module
Used for numerical and array operations (scientific computing).
| Feature | Description |
|---|---|
| ndarray | Multi-dimensional array |
| Fast | Faster than lists |
| Math Ops | Vector operations |
SciPy Module
Built on NumPy, used for advanced scientific calculations.
Applications
- Optimization
- Statistics
- Linear Algebra
- Signal Processing
sys Module
Used to interact with Python interpreter & system.
| Function | Purpose |
|---|---|
| sys.argv | Command-line args |
| sys.exit() | Exit program |
| sys.path | Module search path |
Math Module
Used for mathematical operations.
| Function | Meaning |
|---|---|
| sqrt() | Square root |
| pow() | Power |
| ceil() | Round up |
| floor() | Round down |
| factorial() | Factorial |
String Module
Provides string constants & utilities.
| Constant | Meaning |
|---|---|
| ascii_letters | a–z, A–Z |
| digits | 0–9 |
| punctuation | Special symbols |
List (Built-in List Functions)
| Function | Use |
|---|---|
| len() | Length |
| max() | Maximum |
| min() | Minimum |
| sum() | Sum |
| sorted() | Sort |
Date & Time Module (datetime)
Used to handle date and time.
| Class | Use |
|---|---|
| datetime | Date & time |
| date | Date only |
| time | Time only |
Regular Expressions (re Module)
Used for pattern matching in strings.
match()
Checks pattern only at beginning.
search()
Searches pattern anywhere in string.
replace() (sub method)
Replaces matched pattern.
Regex Comparison Table
| Function | Behavior |
|---|---|
| match() | Beginning only |
| search() | Anywhere |
| sub() | Replace text |
Important Exam Points
- Module = single file
- Package = collection of modules
- NumPy & SciPy used for scientific computing
sysinteracts with interpretermathhandles calculations- Regex used for pattern matching
Frequently Asked Exam Questions
- Define module and package
- Difference between NumPy and SciPy
- Explain random and math module
- What is regex? Explain match & search
- Write short note on sys module
File Handling in Python
File handling means storing data permanently in files and reading/writing data from them.
Why File Handling is Needed
- Data persistence (data is not lost after program ends)
- Handling large data
- Data sharing between programs
File Types in Python
Main Types of Files
| File Type | Description | Example |
|---|---|---|
| Text File | Human readable | .txt, .csv |
| Binary File | Machine readable | .bin, .dat, .jpg |
Creating a File
A file is created using open() function with write mode.
Syntax: file = open("data.txt", "w")
⚠ If file already exists, it is overwritten.
Opening a File
Syntax: file = open("filename", "mode")
Common Modes
r→ readw→ writea→ append
Closing a File
Always close file to free memory.
Syntax: file.close()
Writing Data to File
Reading Data from File
Read Methods
| Method | Use |
|---|---|
| read() | Read entire file |
| readline() | Read one line |
| readlines() | Read all lines |
Renaming a File
Using os module.
Deleting a File
Accessing File Properties
| Function | Description |
|---|---|
| file.name | File name |
| file.mode | File mode |
| file.closed | File status |
File Pointer (File Cursor)
A file pointer indicates current position in the file.
Methods
| Method | Use |
|---|---|
| tell() | Current position |
| seek() | Change position |
File Modes (Detailed Table)
| Mode | Meaning |
|---|---|
| r | Read only |
| w | Write (overwrite) |
| a | Append |
| r+ | Read & write |
| w+ | Write & read |
| a+ | Append & read |
| rb | Read binary |
| wb | Write binary |
Binary Files
Binary files store data in 0s and 1s.
Example: Writing Binary File
Example: Reading Binary File
with Statement (Best Practice)
Automatically closes file.
Text vs Binary File (Exam Table)
| Feature | Text File | Binary File |
|---|---|---|
| Readable | Yes | No |
| Storage | Characters | Bytes |
| Mode | r, w | rb, wb |
Important Exam Points
- File handling provides permanent storage
- Always close file after use
- File pointer tracks read/write position
- Binary files use
rbandwbmodes withstatement is safest
Frequently Asked Exam Questions
- Explain file handling with example
- Difference between text and binary files
- Explain file modes
- What is file pointer?
- Write program to read and write file