Checking your session…
Module 05: Modules, File & Exception Handling

Modules & File Handling

Level: 7 | Version: v1.0 | Author: Meptrasoft


Modules & Packages

A module is a .py file containing reusable code. A package is usually a folder of modules. Together they let us split a project into organized, reusable files.

import Statement

import loads a module. Access its members with module.name.

PYTHON
import math
print(math.sqrt(16))   # 4.0

from...import

Import specific names directly (no module prefix needed).

PYTHON
from math import sqrt, pi
print(sqrt(16))   # 4.0
print(pi)         # 3.14159...

Aliasing Modules

Give a module a shorter name using as.

PYTHON
import datetime as dt
print(dt.date.today())

Python Standard Library

Modules that ship with Python — no installation needed. Common ones:

Module Purpose
math Math functions
random Random numbers
datetime Dates and times
os Operating-system paths
json JSON encode/decode
csv Read/write CSV files

pip and Installing Packages

pip installs third-party packages from PyPI (not in the standard library).

BASH
pip install requests
PYTHON
import requests

Creating Your Own Module

Any .py file you write is a module. Put reusable functions in one file, then import it from another file in the same folder.

calculator.py — your module:

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

def subtract(a, b):
    return a - b

main.py — uses the module:

PYTHON
# main.py
import calculator

print(calculator.add(2, 3))        # 5
print(calculator.subtract(5, 1))   # 4

Import specific functions with from:

PYTHON
from calculator import add, subtract

print(add(2, 3))        # 5 (no calculator. prefix)

Python finds calculator because it sits in the same folder as main.py.

The if __name__ == "__main__": Guard

When Python runs a file directly, it sets that file's __name__ to "__main__". When the file is imported, __name__ is the module's name (e.g. "calculator") instead. This guard runs code only when the file is run directly, not when it is imported.

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

if __name__ == "__main__":
    # runs only when you do: python calculator.py
    print("Testing:", add(2, 3))

Now import calculator gives you the add function without running the test line. Always wrap a module's test/demo code in this guard so importing it does not trigger unwanted output.

Packages

A package is usually a folder of modules. For beginner projects, add an __init__.py file inside the folder. It can be empty, and it clearly marks the folder as a package.

TEXT
mathtools/
    __init__.py
    calculator.py

Import a module from the package using dot notation:

PYTHON
import mathtools.calculator
print(mathtools.calculator.add(2, 3))

from mathtools.calculator import add
print(add(2, 3))

File Handling

Opening Files and File Modes

Use open(path, mode) to open a file. The mode decides what you can do.

Mode Meaning
"r" Read (default); error if file is missing
"w" Write; creates/overwrites the file
"a" Append; adds to the end
"x" Create; error if file already exists
"b" Binary (combine, e.g. "rb")

Reading Files

When working with text files, pass encoding="utf-8". Without it, Python uses the operating system's default encoding (on Windows this is often not UTF-8), so accented letters, emojis, and other non-English characters can read as garbage or raise a UnicodeDecodeError. Being explicit keeps files portable across machines.

PYTHON
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()      # entire file as one string

readline() reads one line; readlines() returns a list of lines. You can also loop directly:

PYTHON
with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

Writing Files

"w" overwrites existing content.

PYTHON
with open("data.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")

Appending to Files

"a" keeps existing content and adds to the end.

PYTHON
with open("data.txt", "a", encoding="utf-8") as f:
    f.write("New line\n")

with Statement

with opens a file and closes it automatically — the recommended way.

PYTHON
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()
# file is closed automatically here

No manual close() needed, even if an error occurs.

CSV Files

Use the csv module for comma-separated data.

PYTHON
import csv

with open("students.csv", "r", encoding="utf-8", newline="") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)   # each row is a list

with open("out.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "CGPA"])
    writer.writerow(["Arun", 8.5])

JSON Files

Use the json module to convert between JSON text and Python objects.

PYTHON
import json

data = {"name": "Arun", "cgpa": 8.5}

with open("student.json", "w", encoding="utf-8") as f:
    json.dump(data, f)        # write dict → JSON

with open("student.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)     # read JSON → dict

json.dumps() / json.loads() work with strings instead of files.

Working with File Paths

Use os.path (or pathlib) for safe, cross-platform paths — do not hardcode \ or /.

PYTHON
import os
path = os.path.join("data", "students.csv")   # "data/students.csv" or "data\\students.csv"
print(os.path.exists(path))

Common Fresher Mistakes

Mistake Problem Correct Understanding
Naming your file math.py, random.py, etc. Shadows the standard-library module Give modules unique names
Forgetting the if __name__ == "__main__": guard Test code runs on import Wrap demo/test code in the guard
Folder missing __init__.py Package setup may confuse beginners Add an __init__.py file for clarity
Opening a file without encoding="utf-8" Garbled text / UnicodeDecodeError Always pass encoding="utf-8"
Using open() without close() or with File may stay open / data not saved Use with open(...)
Expecting "w" mode to keep old content "w" overwrites the whole file Use "a" to append

Quick Points

  • A module is a .py file; a package is usually a folder of modules.
  • import module → use module.name; from module import name → use name directly.
  • as creates an alias.
  • Standard library ships with Python; pip installs external packages.
  • File modes: r read, w overwrite, a append, x create.
  • with open(...) closes the file automatically — prefer it.
  • Use csv for CSV, json for JSON, os.path/pathlib for paths.

Interview Questions

What is the difference between a module and a package?
A module is a single .py file. A package is usually a folder containing modules.
What is the difference between import module and from module import name?
import module requires module.name. from module import name uses name directly.
Why use the with statement for files?
It closes the file automatically, even if an error occurs.
What is the difference between "w" and "a" modes?
"w" overwrites the file. "a" appends to the end.
What is pip?
A tool that installs third-party packages from PyPI.
What does if __name__ == "__main__": do?
It runs the code inside it only when the file is run directly, not when it is imported.
What is the beginner-friendly way to make a folder a package?
Add an __init__.py file to the folder.
Why pass encoding="utf-8" when opening a text file?
It reads/writes text consistently across systems and avoids errors with non-English characters.

Practice

  1. Create a module calculator.py with add and subtract functions.
  2. In another file, import calculator and call calculator.add(2, 3).
  3. Import just add using from calculator import add.
  4. Give calculator an alias with import calculator as calc and use it.
  5. Add an if __name__ == "__main__": block to calculator.py that prints a test result, then confirm it does not run when imported.
  6. Create a folder mathtools/ with an __init__.py and move calculator.py into it; import it as from mathtools.calculator import add.
  7. Open a file with encoding="utf-8" and write a line containing an accented character.
  8. Read a file line by line using a for loop.
  9. Append a new line to an existing file using "a" mode.
  10. Rewrite a manual open() / close() example using with.
  11. Write a dictionary to a JSON file and read it back with the json module.
  12. Build a cross-platform path with os.path.join and check if it exists.

End of Level 7