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

# mymodule.py def add(a, b): return a + b

Step 2: Import module

import mymodule print(mymodule.add(10, 20))

Ways to Import a Module

Import StyleExample
import moduleimport math
from module import namefrom math import sqrt
aliasimport math as m

What is a Package?

A package is a collection of related modules stored in directories.

mypackage/ ├── module1.py ├── module2.py └── __init__.py

Standard Library Modules

Python provides a rich standard library to perform common tasks.

random Module

Used to generate random numbers.

FunctionUse
random()Float between 0–1
randint(a,b)Integer between a and b
choice()Random element
import random print(random.randint(1, 10))

NumPy Module

Used for numerical and array operations (scientific computing).

FeatureDescription
ndarrayMulti-dimensional array
FastFaster than lists
Math OpsVector operations
import numpy as np arr = np.array([1,2,3]) print(arr * 2)

SciPy Module

Built on NumPy, used for advanced scientific calculations.

Applications

  • Optimization
  • Statistics
  • Linear Algebra
  • Signal Processing

from scipy import constants print(constants.pi)

sys Module

Used to interact with Python interpreter & system.

FunctionPurpose
sys.argvCommand-line args
sys.exit()Exit program
sys.pathModule search path
import sys print(sys.version)

Math Module

Used for mathematical operations.

FunctionMeaning
sqrt()Square root
pow()Power
ceil()Round up
floor()Round down
factorial()Factorial
import math print(math.sqrt(16))

String Module

Provides string constants & utilities.

ConstantMeaning
ascii_lettersa–z, A–Z
digits0–9
punctuationSpecial symbols
import string print(string.digits)

List (Built-in List Functions)

FunctionUse
len()Length
max()Maximum
min()Minimum
sum()Sum
sorted()Sort
lst = [3,1,2] print(sorted(lst))

Date & Time Module (datetime)

Used to handle date and time.

ClassUse
datetimeDate & time
dateDate only
timeTime only
from datetime import datetime now = datetime.now() print(now)

Regular Expressions (re Module)

Used for pattern matching in strings.

import re

match()

Checks pattern only at beginning.

import re text = "Python is easy" print(re.match("Python", text))

search()

Searches pattern anywhere in string.

print(re.search("easy", text))

replace() (sub method)

Replaces matched pattern.

print(re.sub("easy", "powerful", text))

Regex Comparison Table

FunctionBehavior
match()Beginning only
search()Anywhere
sub()Replace text

Important Exam Points

  • Module = single file
  • Package = collection of modules
  • NumPy & SciPy used for scientific computing
  • sys interacts with interpreter
  • math handles 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 TypeDescriptionExample
Text FileHuman readable.txt, .csv
Binary FileMachine 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 → read
  • w → write
  • a → append

file = open("data.txt", "r")

Closing a File

Always close file to free memory.

Syntax: file.close()

Writing Data to File

file = open("data.txt", "w") file.write("Welcome to Python") file.close()

Reading Data from File

Read Methods

MethodUse
read()Read entire file
readline()Read one line
readlines()Read all lines
file = open("data.txt", "r") print(file.read()) file.close()

Renaming a File

Using os module.

import os os.rename("data.txt", "newdata.txt")

Deleting a File

import os os.remove("newdata.txt")

Accessing File Properties

FunctionDescription
file.nameFile name
file.modeFile mode
file.closedFile status
print(file.name)

File Pointer (File Cursor)

A file pointer indicates current position in the file.

Methods

MethodUse
tell()Current position
seek()Change position
file = open("data.txt", "r") print(file.tell()) file.seek(0)

File Modes (Detailed Table)

ModeMeaning
rRead only
wWrite (overwrite)
aAppend
r+Read & write
w+Write & read
a+Append & read
rbRead binary
wbWrite binary

Binary Files

Binary files store data in 0s and 1s.

Example: Writing Binary File

file = open("data.bin", "wb") file.write(b"Hello") file.close()

Example: Reading Binary File

file = open("data.bin", "rb") print(file.read()) file.close()

with Statement (Best Practice)

Automatically closes file.

with open("data.txt", "r") as file: print(file.read())

Text vs Binary File (Exam Table)

FeatureText FileBinary File
ReadableYesNo
StorageCharactersBytes
Moder, wrb, wb

Important Exam Points

  • File handling provides permanent storage
  • Always close file after use
  • File pointer tracks read/write position
  • Binary files use rb and wb modes
  • with statement 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