๐ Phase 1: Programming Fundamentals
๐ Topic 10: Python Modules, Packages & File Handling
Welcome back! ๐
So far, you've learned Python fundamentals, functions, data structures, list comprehensions, and functional programming. In this lesson, you'll learn how to organize your code into modules and packages and how to read from and write to files.
These skills are essential for every Data Scientist because real-world projects involve working with multiple Python files, libraries, and datasets stored in files.
๐น 1. What is a Module?
A module is a Python file (".py") that contains functions, variables, or classes that can be reused in other Python programs.
Instead of writing the same code repeatedly, you can create a module once and import it wherever needed.
Example:
Suppose you have a file named
calculator.pydef add(a, b):
return a + b
def subtract(a, b):
return a - b
Now use it in another file:
import calculator
print(calculator.add(10, 5))
Output:
15๐น 2. Importing Modules
Python provides different ways to import modules.
Import the Entire Module
import math
print(math.sqrt(25))
Output:
5.0Import Specific Functions
from math import sqrt
print(sqrt(49))
Output:
7.0Import with an Alias
Aliases make long module names easier to use.
import math as m
print(m.pi)
Output:
3.141592653589793๐น 3. Common Built-in Modules
Some commonly used Python modules are:
โข "math" โ Mathematical operations
โข "random" โ Generate random numbers
โข "datetime" โ Work with dates and times
โข "os" โ Interact with the operating system
โข "sys" โ Access system-specific information
โข "statistics" โ Perform statistical calculations
Example:
import random
print(random.randint(1, 10))
This generates a random integer between 1 and 10.
๐น 4. What is a Package?
A package is a collection of related modules organized into folders.
Example:
project/
โ
โโโ main.py
โโโ utilities/
โ โโโ init.py
โ โโโ calculator.py
โ โโโ helper.py
Packages help organize large Python projects into manageable sections.
๐น 5. File Handling
Most Data Science projects involve reading data from files such as:
โข CSV files
โข Text files
โข Excel files
โข JSON files
Python provides built-in functions for file handling.
๐น 6. Opening a File
Syntax:
open(file_name, mode)Common modes:
Mode | Description
"r" | Read
"w" | Write (overwrites existing content)
"a" | Append
"x" | Create a new file
"rb" | Read binary files
"wb" | Write binary files
๐น 7. Reading a File
Suppose
sample.txt contains:Welcome to Python
Learning File Handling
Python code:
file = open("sample.txt", "r")
print(file.read())
file.close()Output:
Welcome to Python
Learning File Handling
๐น 8. Writing to a File
file = open("sample.txt", "w")
file.write("Hello Data Science!")
file.close()This replaces the previous contents of the file.
๐น 9. Appending to a File
file = open("sample.txt", "a")
file.write("\nPython is awesome!")
file.close()