micheledpierri.com

  • HOME
    • Python
    • Statistics
    • Data Analysis
    • Machine Learning
  • WRITINGS
  • VISIONS
  • ABOUT
Home / Python / Modules, Packages, and File Handling
Children dressed in lab coats are studying a python

Modules, Packages, and File Handling

Lesson Objectives

By the end of this lesson, you will be able to:

  • Import and use Python modules
  • Understand the difference between modules and packages
  • Read from and write to text files
  • Organize code into reusable components

This lesson introduces scalability:

code stops living in a single file and becomes a structured system.


1️⃣ What Is a Module

A module is a Python file that contains:

  • functions
  • variables
  • classes

Every .py file is a module.

Example:

# math.py
def square(x):
    return x * x

You can use it in another file.


2️⃣ Importing Modules

Import the Entire Module

import math
print(math.sqrt(16))

You access module content using dot notation.

Import Specific Objects

from math import sqrt
print(sqrt(16))

Use this carefully to avoid name conflicts.

Aliasing Imports

import numpy as np

This is extremely common in data analysis.


3️⃣ Built-in vs External Modules

Built-in Modules

Python ships with many built-in modules:

  • math
  • os
  • sys
  • random

Example:

import random
random.randint(1, 10)


External Packages

External packages must be installed.

Example (in terminal):

pip install numpy

Then (in code editor):

import numpy as np

This is how the scientific ecosystem works.


4️⃣ What Is a Package

A package is a collection of modules.

Example structure:

my_project/
│
├── analysis/
│   ├── __init__.py
│   ├── stats.py
│   └── preprocessing.py

Packages allow:

  • logical grouping
  • reusable pipelines
  • clean project structure

5️⃣ Reading Files in Python

Reading files is fundamental in data analysis.

Basic File Reading

file = open("data.txt", "r")
content = file.read()
file.close()

This works, but it is not recommended.

Using with (Best Practice)

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

Why with?

  • automatically closes the file
  • safer and cleaner

6️⃣ Writing Files in Python

Writing Text

with open("output.txt", "w") as file:
    file.write("Hello Python")

Mode "w" overwrites existing files.

Appending Text

with open("output.txt", "a") as file:
    file.write("\\nNew line")


7️⃣ Reading Files Line by Line

Useful for large files.

with open("data.txt", "r") as file:
    for line in file:
        print(line.strip())

This pattern is common when processing logs or datasets.


8️⃣ Why This Matters for Data Analysis

Modules and files allow you to:

  • separate logic (clean code)
  • reuse functions across projects
  • load datasets from disk
  • save results and reports

Every serious analytical workflow depends on these concepts.


FAQ — Frequently Asked Questions

Q: What happens if the file does not exist?

A: Python raises a FileNotFoundError.

Q: Should I always use with when opening files?

A: Yes, almost always.

Q: Where should my modules live?

A: Inside the project folder, organized by purpose.

Q: Are CSV and Excel files read this way?

A: Technically yes, but libraries like pandas are preferred.


Exercises

Exercise 1

Import the math module and compute the square root of 25.

Exercise 2

Import only pi from math and print it.

Exercise 3

Create a module utils.py with a function cube(x).

Exercise 4

Import cube in another file and use it.

Exercise 5

Write a file called hello.txt containing "Hello Python".

Exercise 6

Append a second line to the same file.

Exercise 7

Read and print the content of hello.txt.

Exercise 8

Read a file line by line.

Exercise 9

Explain why with is safer than open() + close().

Exercise 10

Explain why modules are essential in large projects.


Solutions

Exercise 1

import math
math.sqrt(25)

Exercise 2

from math import pi
print(pi)

Exercise 3

# utils.py
def cube(x):
    return x ** 3

Exercise 4

from utils import cube
cube(3)

Exercise 5

with open("hello.txt", "w") as f:
    f.write("Hello Python")

Exercise 6

with open("hello.txt", "a") as f:
    f.write("\\nSecond line")

Exercise 7

with open("hello.txt", "r") as f:
    print(f.read())

Exercise 8

with open("hello.txt", "r") as f:
    for line in f:
        print(line.strip())

Exercise 9

# Automatic file closing, fewer errors

Exercise 10

# Modules improve structure, reuse, and maintainability


🚀 Next Lesson Preview

In Lesson 9, we will cover:

  • runtime errors
  • exceptions
  • try / except blocks
  • writing robust and fault-tolerant code

This is where Python code becomes reliable, not just correct.

Cite this article

Pierri, M. D. (2026). Modules, Packages, and File Handling. micheledpierri.com. Permalink

Share:Email·LinkedIn
Previous← Collections: Lists, Tuples, Sets, and DictionariesNextErrors, Exceptions, and Robust Code →
Python
  1. Why Python
  2. Python & VS Code Setup (From Zero to a Professional Environment)
  3. Variables, Naming Rules, and Basic Syntax
  4. Core Data Types in Python
  5. Control Flow: Conditions and Loops
  6. Functions and Code Reusability
  7. Collections: Lists, Tuples, Sets, and Dictionaries
  8. Modules, Packages, and File Handling
  9. Errors, Exceptions, and Robust Code
  10. Object-Oriented Programming (OOP) in Python
  11. Intermediate Python: Writing Clean, Pythonic Code
  12. Python Wrap-Up Lesson: A Mini Cardiology Risk-Factor Audit (Step-by-Step)
© 2024–2026 micheledpierri.com · Privacy Policy · Impressum