Python Modules and the Standard Library
After Completing This Topic
You will understand how import works, be able to use key modules from the Python standard library, and be able to install and manage external packages with pip.
What is a Module?
A module is a single .py file that contains Python code. You can group functions, classes, and variables into a file and then import it into another file to use.
# math_utils.pydef add(a, b): return a + b
def multiply(a, b): return a * b
PI = 3.14159# main.pyimport math_utils
print(math_utils.add(3, 5)) # 8print(math_utils.multiply(4, 7)) # 28print(math_utils.PI) # 3.14159When you import math_utils, Python searches for the math_utils.py file in the same directory, executes it, and then makes the functions/variables inside available for use in the form math_utils.name.
Different Ways to Use import
# 1. Import the entire moduleimport osos.getcwd() # Get the current directory
# 2. Import only specific functionsfrom os.path import join, existsjoin("/home", "user") # '/home/user' β can use `join` instead of `os.path.join`
# 3. Use an aliasimport numpy as npnp.array([1, 2, 3]) # Use `np.array` instead of `numpy.array`
# 4. Import everything (not recommended)from os import * # Risk of name collisions β cannot track where it came fromfrom X import * is convenient, but it makes it impossible to know where the names come from, so it's not recommended for large projects. Explicit imports are always better.
The Standard Library β Tools You Can Use Without Installing
When you install Python, hundreds of modules are installed along with it. This is the Standard Library. It reflects Python's philosophy of "batteries included."
os β Interacting with the Operating System
import os
# Current directoryprint(os.getcwd()) # /home/user/project
# List of filesfiles = os.listdir(".")print(files) # ['main.py', 'data', 'output']
# Create a directoryos.makedirs("output/reports", exist_ok=True)
# Environment variablesdb_host = os.environ.get("DB_HOST", "localhost")os.path β Path Manipulation
import os.path
path = "/home/user/data/report.csv"
os.path.basename(path) # 'report.csv'os.path.dirname(path) # '/home/user/data'os.path.splitext(path) # ('/home/user/data/report', '.csv')os.path.exists(path) # True or Falseos.path.join("data", "output", "file.txt") # 'data/output/file.txt'json β Processing JSON Data
import json
# Python object β JSON stringdata = {"name": "Hoon", "scores": [90, 85, 95]}json_str = json.dumps(data, ensure_ascii=False, indent=2)print(json_str)
# JSON string β Python objectparsed = json.loads(json_str)print(parsed["name"]) # Hoon
# Save to/read from a filewith open("data.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2)
with open("data.json", "r", encoding="utf-8") as f: loaded = json.load(f)You need to include ensure_ascii=False so that Korean characters are saved as they are (e.g., νκΈ) without being escaped.
datetime β Dates and Times
from datetime import datetime, timedelta
# Current timenow = datetime.now()print(now) # 2026-07-03 14:30:00.123456
# Format conversionprint(now.strftime("%Y-%m-%d")) # 2026-07-03print(now.strftime("%Y/%m/%d %H:%M")) # 2026/07/03 14:30
# String β datetimedate = datetime.strptime("2026-07-03", "%Y-%m-%d")
# Date calculationstomorrow = now + timedelta(days=1)week_ago = now - timedelta(weeks=1)diff = datetime(2026, 12, 31) - nowprint(f"D-{diff.days}") # D-181collections β Advanced Data Structures
from collections import Counter, defaultdict
# Counter β Count frequencieswords = ["apple", "banana", "apple", "cherry", "banana", "apple"]count = Counter(words)print(count) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})print(count.most_common(2)) # [('apple', 3), ('banana', 2)]
# defaultdict β Dictionary with default valuesscores = defaultdict(list)scores["math"].append(90)scores["math"].append(85)scores["english"].append(92)print(dict(scores)) # {'math': [90, 85], 'english': [92]}random β Random Number Generation
import random
random.randint(1, 100) # Integer between 1 and 100random.choice(["A", "B", "C"]) # Select one from a listrandom.shuffle([1, 2, 3, 4]) # Shuffle a list in placerandom.sample(range(100), 5) # Select 5 unique items from 0 to 99pip β Installing External Packages
If you need functionality that isn't in the standard library, you can install external packages.
# Installpip install requestspip install pandas numpy matplotlib
# Install a specific versionpip install requests==2.31.0
# Upgradepip install --upgrade requests
# Uninstallpip uninstall requests
# List installed packagespip list
# Manage dependencies with requirements.txtpip freeze > requirements.txt # Record the currently installed packagespip install -r requirements.txt # Install the recorded packagesrequirements.txt is a file that records the external packages used in a project. This allows others (or a server) to reproduce the same environment.
__name__ == "__main__" β Distinguishing Between Execution and Import
# greet.pydef hello(name): print(f"Hello, {name}!")
if __name__ == "__main__": # Only executed when this file is run directly hello("World")$ python greet.py # Prints "Hello, World!"# other.pyimport greet # `hello("World")` is not executedgreet.hello("Python") # Prints "Hello, Python!"When you run python greet.py directly, __name__ becomes "__main__". When you import greet in another file, __name__ becomes "greet". This pattern separates "test code that runs when executed directly" from "functionality that is used when imported as a module."
Key Takeaways
| Concept | Summary |
|---|---|
| Module | One .py file = One module |
import | Bring in code from another file |
| Standard Library | Collection of modules that you can use without installing (os, json, datetime, etc.) |
pip | Tool for installing and managing external packages |
requirements.txt | Records project dependencies |
__name__ | Distinguishes between direct execution and import |
One of Python's strengths is its rich standard library and the vast third-party ecosystem (500,000+ packages on PyPI). Follow the principle of "don't reinvent the wheel" β always search the standard library and PyPI before implementing something yourself. This will increase your productivity.
Practical Pattern β Combining Multiple Modules
In practice, it's rare to use only one module. It's common to combine multiple standard libraries.
import osimport jsonfrom datetime import datetime
def process_data_files(directory): results = [] for filename in os.listdir(directory): if not filename.endswith(".json"): continue filepath = os.path.join(directory, filename) with open(filepath, "r", encoding="utf-8") as f: data = json.load(f) results.append({ "file": filename, "records": len(data), "processed_at": datetime.now().strftime("%Y-%m-%d %H:%M") }) return results
# output:# [# {"file": "users.json", "records": 150, "processed_at": "2026-07-03 14:30"},# {"file": "orders.json", "records": 423, "processed_at": "2026-07-03 14:30"}# ]os is used to browse files, json is used to read them, and datetime is used to record the time β these three modules work together seamlessly. This is the basic pattern for writing scripts.