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.
import math
print(math.sqrt(16)) # 4.0
from...import
Import specific names directly (no module prefix needed).
from math import sqrt, pi
print(sqrt(16)) # 4.0
print(pi) # 3.14159...
Aliasing Modules
Give a module a shorter name using as.
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).
pip install requests
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:
# calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
main.py — uses the module:
# main.py
import calculator
print(calculator.add(2, 3)) # 5
print(calculator.subtract(5, 1)) # 4
Import specific functions with from:
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.
# 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.
mathtools/
__init__.py
calculator.py
Import a module from the package using dot notation:
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.
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:
with open("data.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
Writing Files
"w" overwrites existing content.
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.
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.
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.
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.
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 /.
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
.pyfile; a package is usually a folder of modules. import module→ usemodule.name;from module import name→ usenamedirectly.ascreates an alias.- Standard library ships with Python;
pipinstalls external packages. - File modes:
rread,woverwrite,aappend,xcreate. with open(...)closes the file automatically — prefer it.- Use
csvfor CSV,jsonfor JSON,os.path/pathlibfor paths.
Interview Questions
- What is the difference between a module and a package?
- A module is a single
.pyfile. A package is usually a folder containing modules. - What is the difference between
import moduleandfrom module import name? import modulerequiresmodule.name.from module import nameusesnamedirectly.- Why use the
withstatement 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__.pyfile 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
- Create a module
calculator.pywithaddandsubtractfunctions. - In another file,
import calculatorand callcalculator.add(2, 3). - Import just
addusingfrom calculator import add. - Give
calculatoran alias withimport calculator as calcand use it. - Add an
if __name__ == "__main__":block tocalculator.pythat prints a test result, then confirm it does not run when imported. - Create a folder
mathtools/with an__init__.pyand movecalculator.pyinto it; import it asfrom mathtools.calculator import add. - Open a file with
encoding="utf-8"and write a line containing an accented character. - Read a file line by line using a
forloop. - Append a new line to an existing file using
"a"mode. - Rewrite a manual
open()/close()example usingwith. - Write a dictionary to a JSON file and read it back with the
jsonmodule. - Build a cross-platform path with
os.path.joinand check if it exists.
End of Level 7