Back to List

Python Modules and Standard Library

Learn how to import modules, use the standard library, and manage external packages with pip in Python.

Intermediate
|
10min
|
Verified (2026-07)
moduleimportstandard librarypippackage management
Progress0/18 (0%)

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.

python
# math_utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
PI = 3.14159
python
# main.py
import math_utils
print(math_utils.add(3, 5)) # 8
print(math_utils.multiply(4, 7)) # 28
print(math_utils.PI) # 3.14159

When 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

python
# 1. Import the entire module
import os
os.getcwd() # Get the current directory
# 2. Import only specific functions
from os.path import join, exists
join("/home", "user") # '/home/user' β€” can use `join` instead of `os.path.join`
# 3. Use an alias
import numpy as np
np.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 from

from 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

python
import os
# Current directory
print(os.getcwd()) # /home/user/project
# List of files
files = os.listdir(".")
print(files) # ['main.py', 'data', 'output']
# Create a directory
os.makedirs("output/reports", exist_ok=True)
# Environment variables
db_host = os.environ.get("DB_HOST", "localhost")

os.path β€” Path Manipulation

python
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 False
os.path.join("data", "output", "file.txt") # 'data/output/file.txt'

json β€” Processing JSON Data

python
import json
# Python object β†’ JSON string
data = {"name": "Hoon", "scores": [90, 85, 95]}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# JSON string β†’ Python object
parsed = json.loads(json_str)
print(parsed["name"]) # Hoon
# Save to/read from a file
with 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

python
from datetime import datetime, timedelta
# Current time
now = datetime.now()
print(now) # 2026-07-03 14:30:00.123456
# Format conversion
print(now.strftime("%Y-%m-%d")) # 2026-07-03
print(now.strftime("%Y/%m/%d %H:%M")) # 2026/07/03 14:30
# String β†’ datetime
date = datetime.strptime("2026-07-03", "%Y-%m-%d")
# Date calculations
tomorrow = now + timedelta(days=1)
week_ago = now - timedelta(weeks=1)
diff = datetime(2026, 12, 31) - now
print(f"D-{diff.days}") # D-181

collections β€” Advanced Data Structures

python
from collections import Counter, defaultdict
# Counter β€” Count frequencies
words = ["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 values
scores = 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

python
import random
random.randint(1, 100) # Integer between 1 and 100
random.choice(["A", "B", "C"]) # Select one from a list
random.shuffle([1, 2, 3, 4]) # Shuffle a list in place
random.sample(range(100), 5) # Select 5 unique items from 0 to 99

pip β€” Installing External Packages

If you need functionality that isn't in the standard library, you can install external packages.

bash
# Install
pip install requests
pip install pandas numpy matplotlib
# Install a specific version
pip install requests==2.31.0
# Upgrade
pip install --upgrade requests
# Uninstall
pip uninstall requests
# List installed packages
pip list
# Manage dependencies with requirements.txt
pip freeze > requirements.txt # Record the currently installed packages
pip install -r requirements.txt # Install the recorded packages

requirements.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

python
# greet.py
def hello(name):
print(f"Hello, {name}!")
if __name__ == "__main__":
# Only executed when this file is run directly
hello("World")
bash
$ python greet.py # Prints "Hello, World!"
python
# other.py
import greet # `hello("World")` is not executed
greet.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

ConceptSummary
ModuleOne .py file = One module
importBring in code from another file
Standard LibraryCollection of modules that you can use without installing (os, json, datetime, etc.)
pipTool for installing and managing external packages
requirements.txtRecords 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.

python
import os
import json
from 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.

πŸ’¬ Questions & Comments

0 comments

You can post without signing in. Guest comments cannot be edited or deleted by their author.

0/2000

Loading...