Adv-Python Unit 3: Complete Concept Guide
Unit III: Python Modules and File Handling -> Generated and Prepared By Thiruselvan (ThiruXD)
1. Introduction to Python Modules
1.1 What is a Module?
A module is a Python file (with .py extension) that contains:
- Functions
- Classes
- Variables
- Executable statements
The file name becomes the module name without the .py extension. For example, calculator.py becomes the module calculator.
Key Insight: A module is not a separate programming language. It is simply a Python file that can be reused by importing it into another Python file.
1.2 Why Use Modules?
| Reason | Explanation | Example |
|---|---|---|
| Code Reuse | Write once, use in many programs | Same tax calculation function in multiple billing programs |
| Organisation | Separate large programs into logical files | Database code, validation code, report code in separate modules |
| Maintainability | Change one module without rewriting the full application | Update one email-sending module used across the project |
| Testing | Test individual modules independently | Test calculator functions before using in main program |
| Teamwork | Different developers work on different modules | One developer on login.py, another on reports.py |
1.3 Module, Package, and Library
| Concept | Meaning | Simple Example |
|---|---|---|
| Module | One Python file | math_tools.py |
| Package | A folder grouping related modules (usually contains __init__.py) | data_utils/ folder with cleaning.py, validation.py |
| Library | A collection of modules and packages for specific tasks | NumPy, Pandas, Matplotlib |
Hierarchy: Library ⊃ Package ⊃ Module
1.4 Python Module Workflow
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌──────────────┐ ┌─────────────┐
│ 1. Create │ → │ 2. Write & │ → │ 3. Package │ → │ 4. Distribute│ → │ 5. Import & │
│ Module │ │ Test │ │ Module │ │ │ │ Reuse │
└─────────────┘ └─────────────┘ └─────────────┘ └──────────────┘ └─────────────┘
↑ │
└────────────────────── Iterate & Improve ─────────────────────────────────┘Step 1: Create Module — Write functions, classes, and variables in a .py file.
Step 2: Write & Test — Test with different inputs to verify correctness and reliability.
Step 3: Package Module — Organize into standard directory structure with __init__.py, metadata files.
Step 4: Distribute — Share through PyPI or private repository; version release.
Step 5: Import & Reuse — Import into multiple programs using pip install and import.
Iterate & Improve — Fix bugs, optimize, add features; update, test, repackage, redistribute.
2. Creating and Using Modules
2.1 Steps to Create a Module
- Create a new Python file with a meaningful name (e.g.,
mymath.py). - Define functions, variables, or classes inside the file.
- Save the file in the same folder as the program that will use it.
- Use the
importstatement in another Python file. - Access module members using dot notation:
module_name.function_name().
2.2 Example: User-Defined Module
File: calculator_tools.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
PI = 3.14159File: main.py
import calculator_tools
print(calculator_tools.add(10, 5)) # 15
print(calculator_tools.subtract(10, 5)) # 5
print(calculator_tools.PI) # 3.141592.3 Explanation Table
| Part of Program | Role |
|---|---|
calculator_tools.py | Module file containing reusable functions and variables |
main.py | Main program that imports and uses the module |
import calculator_tools | Loads the module into the program |
calculator_tools.add(10, 5) | Calls the add function using dot notation |
2.4 Best Practices for Creating Modules
- Keep each module focused on one main purpose.
- Use meaningful function and variable names.
- Avoid writing too much executable code directly at module level.
- Add comments or docstrings to explain important functions.
- Test the module independently before using it in a larger project.
3. Naming and Renaming Modules
3.1 Module Naming Rules
| Rule | Correct Example | Incorrect Example |
|---|---|---|
| Use lowercase letters | student_records.py | StudentRecords.py |
| Use underscores for readability | file_utils.py | file-utils.py |
| Do not begin with a number | module3_notes.py | 3module.py |
| Avoid spaces | data_cleaning.py | data cleaning.py |
| Avoid names of built-in modules | my_math_tools.py | math.py |
3.2 Renaming Modules Using Aliases
Python allows an imported module to be given a shorter name using the as keyword. This does not rename the original file; it only creates an alias inside the current program.
import math as m
print(m.sqrt(25)) # 5.0
print(m.pi) # 3.14159...
import random as rd
number = rd.randint(1, 10)
print(number)Common Aliases:
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt
Important: Do not create files named math.py, random.py, json.py, or re.py in your project folder. These names can hide the original built-in modules and cause confusing errors.
4. Variables in Modules, Built-in Modules, and dir() Function
4.1 Variables in Modules
A module can store variables just like a normal Python program. These variables can be accessed after importing the module. Module-level variables are useful for:
- Constants
- Configuration values
- Version numbers
- Shared settings
File: college_info.py
college_name = "ABC Institute"
course = "Python Programming"
semester = 5File: main.py
import college_info
print(college_info.college_name) # ABC Institute
print(college_info.course) # Python Programming
print(college_info.semester) # 54.2 Built-in Modules
Python includes many ready-to-use modules in its standard library.
| Built-in Module | Purpose | Example Use |
|---|---|---|
math | Mathematical functions and constants | sqrt(), ceil(), pi |
random | Random number generation | randint(), choice(), shuffle() |
datetime | Dates and times | date.today(), datetime.now() |
os | Operating system interaction | listdir(), mkdir(), path.exists() |
sys | Python interpreter information | sys.version, sys.path |
json | JSON parsing and conversion | loads(), dumps(), load(), dump() |
re | Regular expression operations | search(), findall(), sub() |
statistics | Basic statistics | mean(), median(), mode() |
Examples:
import math
print(math.sqrt(64)) # 8.0
import random
print(random.choice(["red", "blue", "green"]))
from datetime import date
print(date.today())4.3 The dir() Function
The dir() function returns a list of names available inside an object or module. It is useful for exploring what functions, classes, constants, and attributes are provided by a module.
import math
print(dir(math))
print(math.sqrt(16))Use of dir() | Meaning |
|---|---|
dir(math) | Displays names available in the math module |
dir(str) | Displays methods available for string objects |
dir() | Displays names available in the current scope |
5. Importing from Modules
5.1 Types of Import Statements
| Import Style | Syntax | When to Use |
|---|---|---|
| Import full module | import math | When many functions from the module are required |
| Import with alias | import math as m | When a shorter name improves readability |
| Import one name | from math import sqrt | When only one function or variable is needed |
| Import multiple names | from math import sqrt, pi | When a few selected names are needed |
| Import all names | from math import * | Generally avoided; can create name conflicts |
Examples:
# Import full module
import math
print(math.sqrt(81)) # 9.0
# Import specific names
from math import sqrt, pi
print(sqrt(81)) # 9.0
print(pi) # 3.14159...
# Import with alias
import math as m
print(m.factorial(5)) # 1205.2 The __name__ Variable
When a Python file is run directly, its special variable __name__ is set to "__main__". When the same file is imported as a module, __name__ becomes the module name. This allows a file to contain test code that runs only when the file is executed directly.
File: greetings.py
def welcome(name):
return "Welcome, " + name
if __name__ == "__main__":
print(welcome("Student"))Why it matters: The __name__ == "__main__" pattern prevents test code from running automatically when a module is imported into another program.
6. JSON in Python
6.1 What is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight text format used for storing and exchanging structured data. JSON is widely used in:
- Web applications
- APIs
- Configuration files
- Databases
- Data transfer between systems
6.2 JSON Data Types and Python Mapping
| JSON Type | Python Equivalent | Example |
|---|---|---|
| object | dict | {"name": "Amit"} |
| array | list | [10, 20, 30] |
| string | str | "Python" |
| number | int or float | 25 or 3.14 |
| true / false | True / False | true becomes True |
| null | None | null becomes None |
6.3 The json Module
| Function | Purpose |
|---|---|
json.loads() | Parses a JSON string and converts it into a Python object |
json.dumps() | Converts a Python object into a JSON-formatted string |
json.load() | Reads JSON data from a file and converts it into a Python object |
json.dump() | Writes a Python object into a file in JSON format |
Memory Aid:
- loads/dumps → work with strings (the ‘s’ stands for string)
- load/dump → work with files
6.4 Parsing JSON Strings
import json
student_json = '{"name": "Ravi", "age": 21, "marks": 88}'
student = json.loads(student_json)
print(student["name"]) # Ravi
print(student["marks"]) # 886.5 Converting Python to JSON
import json
student = {
"name": "Ravi",
"age": 21,
"marks": 88
}
json_string = json.dumps(student, indent=4)
print(json_string)6.6 Parsing Nested JSON
import json
data = '''
{
"student": {
"name": "Meena",
"age": 20,
"subjects": ["Python", "DBMS", "AI"]
}
}
'''
obj = json.loads(data)
print(obj["student"]["name"]) # Meena
print(obj["student"]["subjects"][0]) # Python6.7 Reading and Writing JSON Files
import json
# Writing JSON to file
student = {
"name": "Meena",
"semester": 5,
"skills": ["Python", "SQL"]
}
with open("student.json", "w") as file:
json.dump(student, file, indent=4)
# Reading JSON from file
with open("student.json", "r") as file:
data = json.load(file)
print(data["skills"]) # ['Python', 'SQL']6.8 JSON Errors and Solutions
| Common JSON Error | Reason | Solution |
|---|---|---|
JSONDecodeError | Invalid JSON syntax (missing quotes, extra comma) | Validate JSON format before parsing |
KeyError | Trying to access a key that does not exist | Use get() or check if key exists |
TypeError | Trying to serialize an unsupported Python object | Convert object to a serializable type |
Safer way to read optional values:
name = data.get("name", "Unknown")
print(name)7. Regular Expressions and RegEx Functions
7.1 What is a Regular Expression?
A Regular Expression (RegEx) is a pattern used to match text. It is useful for:
- Validating input (emails, phone numbers)
- Extracting values from text
- Searching documents
- Cleaning text
- Replacing unwanted content
7.2 Regular Expression Workflow
┌───────────┐ ┌───────────┐ ┌──────────────┐ ┌─────────────────┐ ┌──────────────┐
│ 1. Pattern│ → │ 2. Compile│ → │ 3. Search/ │ → │ 4. Process/ │ → │ 5. Validate/ │
│ Define │ │ Pattern │ │ Match │ │ Extract │ │ Output │
└───────────┘ └───────────┘ └──────────────┘ └─────────────────┘ └──────────────┘Step 1: Pattern — Define the regular expression pattern. Step 2: Compile — Compile the pattern into a regex object. Step 3: Search/Match — Search the target string for matches. Step 4: Process/Extract — Process the matches or extract the needed information. Step 5: Validate/Output — Validate results and output or store them.
7.3 RegEx Metacharacters
| Symbol | Meaning | Example |
|---|---|---|
. | Matches any single character except newline | a.c matches abc, axc |
^ | Matches the start of a string | ^Hello |
$ | Matches the end of a string | end$ |
* | Matches zero or more repetitions | ab* matches a, ab, abb |
+ | Matches one or more repetitions | ab+ matches ab, abb |
? | Matches zero or one repetition | colou?r matches color or colour |
[] | Matches one character from a set | [aeiou] |
\d | Matches a digit | \d+ matches 123 |
\w | Matches a word character | \w+ |
\s | Matches whitespace | \s+ |
7.4 Common Functions in the re Module
| Function | Purpose |
|---|---|
re.search(pattern, text) | Searches anywhere in the string; returns first match |
re.match(pattern, text) | Checks for a match only at the beginning of the string |
re.fullmatch(pattern, text) | Checks whether the entire string matches the pattern |
re.findall(pattern, text) | Returns all matching substrings as a list |
re.finditer(pattern, text) | Returns match objects one by one for all matches |
re.split(pattern, text) | Splits a string based on the pattern |
re.sub(pattern, replacement, text) | Replaces matching text with new text |
re.compile(pattern) | Compiles a pattern for repeated use |
7.5 RegEx Examples
Example 1: Find all numbers
import re
text = "My marks are 85 and my attendance is 92"
numbers = re.findall(r"\d+", text)
print(numbers) # ['85', '92']Example 2: Validate email
import re
email = "student@example.com"
pattern = r"^[\w.-]+@[\w.-]+\.\w+$"
if re.fullmatch(pattern, email):
print("Valid email")
else:
print("Invalid email")Example 3: Clean whitespace
import re
sentence = "Python is easy"
cleaned = re.sub(r"\s+", " ", sentence)
print(cleaned) # Python is easyRaw Strings: RegEx patterns are usually written as raw strings using r"pattern". This avoids confusion with Python escape characters such as \n and \t.
8. Exception Handling
8.1 What is an Exception?
An exception is an error that occurs while a program is running. Without exception handling, the program stops immediately. With exception handling, the program can:
- Display a meaningful message
- Recover from the error
- Close resources safely
8.2 Basic try-except Structure
try:
number = int(input("Enter a number: "))
print(100 / number)
except ValueError:
print("Please enter only numbers.")
except ZeroDivisionError:
print("Cannot divide by zero.")8.3 Common Exceptions in Python
| Exception | When It Occurs | Example |
|---|---|---|
ValueError | Correct type but invalid value | int("abc") |
ZeroDivisionError | Division by zero | 10 / 0 |
FileNotFoundError | File does not exist | open("missing.txt") |
KeyError | Dictionary key is missing | student["age"] when age is absent |
IndexError | List index is out of range | items[10] |
TypeError | Operation on incompatible types | "5" + 2 |
8.4 Multiple Exceptions
Multiple except blocks are used when different errors require different responses. Python checks the except blocks from top to bottom and runs the first matching block.
try:
x = int(input("Enter number: "))
y = int(input("Enter divisor: "))
print(x / y)
except ValueError:
print("Invalid input.")
except ZeroDivisionError:
print("Cannot divide by zero.")
except Exception as e:
print("Unexpected error:", e)8.5 else and finally Blocks
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully.")
finally:
print("Program finished.")elseblock: Runs only if no exception occurs.finallyblock: Runs whether or not an exception occurs. Commonly used to close files, release resources, or display final messages.
8.6 Raising Exceptions
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
print(set_age(20)) # 20
# print(set_age(-5)) # Raises ValueErrorBest Practice: Avoid using a bare except: block because it catches all errors and can hide programming mistakes. Catch specific exceptions whenever possible.
9. File Handling
9.1 What is File Handling?
File handling allows a program to store data permanently and read data from external sources. Python can work with text files, CSV files, JSON files, binary files, logs, and many other formats.
9.2 Safe File Handling Workflow
┌──────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ 1. Open │ → │ 2. Read/ │ → │ 3. Process │ → │ 4. Close │ → │ 5. Handle │
│ File │ │ Write │ │ Data │ │ Safely │ │ Errors │
└──────────┘ └──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘Step 1: Open File — Open in appropriate mode (read, write, append). Step 2: Read/Write — Read from or write to the file as required. Step 3: Process Data — Process, validate, or transform data as needed. Step 4: Close Safely — Close the file to release resources and ensure data is saved. Step 5: Handle Errors — Catch and handle exceptions to prevent crashes and ensure reliability.
9.3 File Opening Modes
| Mode | Meaning | Use Case |
|---|---|---|
r | Read mode. File must exist | Read an existing text file |
w | Write mode. Creates or overwrites file | Save new output |
a | Append mode. Adds content at the end | Add log messages |
x | Create mode. Fails if file exists | Create a new file safely |
b | Binary mode | Read images, audio, binary data |
t | Text mode (default) | Read normal text files |
+ | Read and write mode | Update file content |
9.4 Opening and Closing Files
The open() function is used to open a file. It returns a file object. Files should be closed after use to avoid resource leakage. The recommended method is to use the with statement because it closes the file automatically.
# Using with statement (recommended)
with open("students.txt", "r") as file:
print(file.read())
# Manual opening and closing
file = open("students.txt", "r")
print(file.read())
file.close()9.5 Reading Files
# Read entire file
with open("students.txt", "r") as file:
print(file.read())
# Read one line
with open("students.txt", "r") as file:
print(file.readline())
# Read line by line
with open("students.txt", "r") as file:
for line in file:
print(line.strip())9.6 Writing and Appending Files
# Writing (overwrites existing content)
with open("output.txt", "w") as file:
file.write("First line\n")
file.write("Second line\n")
# Appending (adds to end)
with open("output.txt", "a") as file:
file.write("Appended line\n")9.7 Working with File Paths and Encoding
A file path tells Python where the file is located. If only the file name is given, Python searches in the current working directory. For text files, UTF-8 encoding is commonly used because it supports many languages and symbols.
from pathlib import Path
path = Path("data") / "students.txt"
with open(path, "r", encoding="utf-8") as file:
content = file.read()
print(content)9.8 File Handling with Exceptions
try:
with open("marks.txt", "r") as file:
marks = file.read()
print(marks)
except FileNotFoundError:
print("The file marks.txt was not found.")9.9 Important File Handling Concepts
| Concept | Explanation |
|---|---|
| Current working directory | The folder from which the Python program is currently running |
| Absolute path | Full path from the root of the system |
| Relative path | Path relative to the current working directory |
| Encoding | Rule used to convert text into bytes and bytes into text |
| Buffering | Temporary storage used while reading or writing data |
10. Integrated Practical Example
The following example combines important concepts: importing modules, reading JSON data, validating email using RegEx, handling exceptions, and writing output to a file.
import json
import re
EMAIL_PATTERN = r"^[\w.-]+@[\w.-]+\.\w+$"
try:
with open("students.json", "r", encoding="utf-8") as file:
students = json.load(file)
valid_students = []
for student in students:
email = student.get("email", "")
if re.fullmatch(EMAIL_PATTERN, email):
valid_students.append(student)
with open("valid_students.json", "w", encoding="utf-8") as file:
json.dump(valid_students, file, indent=4)
print("Valid student records saved successfully.")
except FileNotFoundError:
print("Input JSON file not found.")
except json.JSONDecodeError:
print("Invalid JSON format.")
except Exception as error:
print("Unexpected error:", error)Concepts Demonstrated
| Concept Used | Where It Appears in the Program |
|---|---|
| Module import | json and re modules imported at the beginning |
| JSON parsing | json.load(file) reads JSON from a file into Python objects |
| RegEx validation | re.fullmatch() checks whether the email format is valid |
| File writing | json.dump() writes valid records into a new JSON file |
| Exception handling | Specific except blocks handle missing file and invalid JSON |
11. Unit Summary
PYTHON MODULES AND FILE HANDLING
│
├── Introduction to Modules
│ ├── Definition (.py file with reusable code)
│ ├── Importance (reuse, organisation, maintainability, testing, teamwork)
│ └── Module vs Package vs Library
│
├── Creating and Using Modules
│ ├── Steps to create
│ ├── User-defined module example
│ └── Best practices
│
├── Naming and Renaming Modules
│ ├── Naming rules
│ └── Aliases (as keyword)
│
├── Variables, Built-in Modules, dir()
│ ├── Module-level variables
│ ├── Common built-in modules
│ └── dir() function
│
├── Importing from Modules
│ ├── Import styles
│ └── __name__ == "__main__" pattern
│
├── JSON in Python
│ ├── JSON data types → Python mapping
│ ├── json.loads/dumps/load/dump
│ ├── Nested JSON parsing
│ ├── File read/write
│ └── Error handling
│
├── Regular Expressions
│ ├── Metacharacters
│ ├── re module functions
│ └── Examples (findall, fullmatch, sub)
│
├── Exception Handling
│ ├── try-except
│ ├── Multiple exceptions
│ ├── else, finally
│ └── Raising exceptions
│
└── File Handling
├── Modes (r, w, a, x, b, t, +)
├── Reading, writing, appending
├── File paths and encoding
└── File handling with exceptions12. Key Formulas and Syntax — Quick Reference
| Concept | Syntax/Example |
|---|---|
| Import full module | import math |
| Import with alias | import math as m |
| Import specific names | from math import sqrt, pi |
| Import all | from math import * |
| Module variable access | module_name.variable |
| List module contents | dir(module_name) |
| Main guard | if __name__ == "__main__": |
| Parse JSON string | json.loads(json_string) |
| Convert to JSON string | json.dumps(python_obj) |
| Read JSON file | json.load(file) |
| Write JSON file | json.dump(obj, file, indent=4) |
| RegEx search | re.search(pattern, text) |
| RegEx match at start | re.match(pattern, text) |
| RegEx full match | re.fullmatch(pattern, text) |
| RegEx find all | re.findall(pattern, text) |
| RegEx replace | re.sub(pattern, replacement, text) |
| RegEx split | re.split(pattern, text) |
| RegEx compile | re.compile(pattern) |
| Try-except | try: ... except ValueError: ... |
| Try-except-else-finally | try: ... except: ... else: ... finally: ... |
| Raise exception | raise ValueError("message") |
| Open file (read) | with open("file.txt", "r") as f: |
| Open file (write) | with open("file.txt", "w") as f: |
| Open file (append) | with open("file.txt", "a") as f: |
| Read entire file | f.read() |
| Read one line | f.readline() |
| Read line by line | for line in f: |
| Write to file | f.write("text") |
| File path | Path("data") / "students.txt" |
| Encoding | open(path, "r", encoding="utf-8") |
13. Exam-Focused Points
- Module definition — A
.pyfile with reusable code. - Module vs Package vs Library — Module = file; Package = folder; Library = collection.
importvsfrom ... import— Full module vs specific names.- Aliases —
import numpy as np; does not rename the file. dir()function — Lists module contents.__name__ == "__main__"— Prevents test code from running on import.- JSON functions —
loads/dumpsfor strings;load/dumpfor files. - JSON data type mapping —
null→None;true→True. - RegEx metacharacters —
.,^,$, ,+,?,[],\d,\w,\s. refunctions —search,match,fullmatch,findall,sub,split,compile.- Raw strings — Use
r"pattern"to avoid escape character issues. - Exception types —
ValueError,ZeroDivisionError,FileNotFoundError,KeyError,IndexError,TypeError. elsevsfinally—elseruns if no exception;finallyalways runs.- File modes —
r(read),w(write/overwrite),a(append),x(create),b(binary),t(text),+(read/write). withstatement — Automatically closes files.- Encoding — UTF-8 for multilingual text.
- Avoid bare
except:— Catch specific exceptions. - Integrated example — Combines modules, JSON, RegEx, exceptions, and file handling.
14. Glossary of Key Terms
| Term | Definition |
|---|---|
| Module | A Python file with a .py extension containing reusable code |
| Package | A folder that groups related modules |
| Library | A collection of modules and packages for specific tasks |
| Import | Bringing code from one module into another program |
| Alias | An alternate short name given using the as keyword |
| Built-in Module | A module included with Python installation |
dir() Function | Lists names and attributes available inside an object or module |
| JSON | JavaScript Object Notation; lightweight text format for structured data |
| Regular Expression | A pattern language for searching, validating, extracting, and replacing text |
| Exception | An error detected during program execution |
| File Handling | Opening, reading, writing, appending, and closing files |
__name__ | Special variable set to "__main__" when file is run directly |
try-except | Block for handling exceptions |
finally | Block that always runs, whether exception occurs or not |
with statement | Context manager that auto-closes files |