標準ライブラリの基本(パート 1)
Python の最大の特徴の 1 つは「Batteries Included」です——すべての Python インストールに完全な標準ライブラリ一式が付属しています。このレッスンでは、最もよく使われる 4 つのモジュール——
random、time、sys、os——をカバーします。それぞれの最も人気のある関数だけを学んでも、多くの実世界の問題を解決するのに役立ちます。
1. random — 乱数
PYTHON
import random
# ランダムな浮動小数点数 [0, 1)
print(random.random()) # 0.3745...
# ランダムな整数 [a, b](両端含む)
print(random.randint(1, 10)) # 1 から 10 の間のランダムな整数
# ランダムな選択
fruits = ["apple", "banana", "orange", "grape"]
print(random.choice(fruits)) # ランダムに 1 つ選ぶ
# ランダムなサンプル(非復元抽出)
print(random.sample(fruits, 2)) # ランダムに 2 つ選ぶ
# 順序をシャッフル
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(cards)
print(cards) # 順序がシャッフルされる
例:抽選プログラム(難易度 ⭐)
PYTHON
import random
# 抽選プール
participants = ["Alice", "Bob", "Charlie", "Diana", "Eve",
"Frank", "Grace", "Henry"]
# 1 等 — 1 名
first = random.choice(participants)
print(f"🎉 1st Prize: {first}")
# 2 等 — 2 名(1 等を除く)
remaining = [p for p in participants if p != first]
second = random.sample(remaining, 2)
print(f"🎊 2nd Prize: {' & '.join(second)}")
# 3 等 — 3 名
remaining = [p for p in remaining if p not in second]
third = random.sample(remaining, 3)
print(f"🎁 3rd Prize: {' & '.join(third)}")
2. time — 時間処理
PYTHON
import time
# 現在のタイムスタンプ(1970-01-01 からの秒数)
print(time.time()) # 1758588800.123
# 実行を一時停止(秒)
print("Start")
time.sleep(1) # 1 秒停止
print("1 second later")
# 現在時刻のフォーマット
print(time.strftime("%Y-%m-%d %H:%M:%S")) # 2026-06-23 16:00:00
例:タイマー(難易度 ⭐)
PYTHON
import time
def countdown(seconds):
"""カウントダウンタイマー"""
while seconds > 0:
print(f"\r⏱ {seconds} seconds left", end="")
time.sleep(1)
seconds -= 1
print("\r⏰ Time's up!")
# コードの実行時間を計測
start = time.time()
total = sum(range(1000000))
end = time.time()
print(f"Execution time: {end - start:.4f} seconds")
3. sys — システム操作
PYTHON
import sys
# Python バージョン
print(sys.version) # 3.13.0 ...
# コマンドライン引数(python script.py a b c のとき)
print(sys.argv) # ['script.py', 'a', 'b', 'c']
# プログラムを終了
# sys.exit(0) # 正常終了
# 標準入力
# line = sys.stdin.readline() # 1 行入力を受け付ける
例:コマンドライン電卓(難易度 ⭐⭐)
PYTHON
import sys
def main():
# 使い方:python calculator.py 3 + 5
if len(sys.argv) != 4:
print("Usage: python calculator.py num1 operator num2")
print("Example: python calculator.py 3 + 5")
return
a = float(sys.argv[1])
op = sys.argv[2]
b = float(sys.argv[3])
if op == "+":
result = a + b
elif op == "-":
result = a - b
elif op == "*":
result = a * b
elif op == "/":
if b == 0:
print("Error: cannot divide by zero")
return
result = a / b
else:
print(f"Unsupported operator: {op}")
return
print(f"{a} {op} {b} = {result}")
if __name__ == "__main__":
main()
4. os — オペレーティングシステム
PYTHON
import os
# 現在の作業ディレクトリ
print(os.getcwd()) # D:\project
# ディレクトリ変更
# os.chdir("/tmp")
# ディレクトリ内容を一覧
for item in os.listdir("."):
print(item)
# ディレクトリ作成
# os.mkdir("new_folder")
# パスの確認
print(os.path.exists("test.txt")) # True
print(os.path.isfile("test.txt")) # True
print(os.path.isdir("data")) # True
# パスを結合
path = os.path.join("data", "files", "test.txt")
print(path) # data/files/test.txt
例:バッチファイル名変更(難易度 ⭐⭐)
PYTHON
import os
def batch_rename(directory, prefix):
"""ディレクトリ内のすべての .txt ファイルの名前を一括変更"""
files = [f for f in os.listdir(directory) if f.endswith(".txt")]
for i, filename in enumerate(files, 1):
old_path = os.path.join(directory, filename)
new_name = f"{prefix}_{i:03d}.txt"
new_path = os.path.join(directory, new_name)
os.rename(old_path, new_path)
print(f" {filename} → {new_name}")
print("Batch rename example (display only, not executed):")
print("Iterate all .txt files, rename to prefix_001.txt format")
よくあるユースケース
- random:抽選、CAPTCHA、ランダムテストデータ生成、ランダムゲームイベント
- time:遅延実行、パフォーマンス計測、タイマー、スケジュールタスク
- sys:コマンドライン引数の読み取り、プログラム終了制御、Python 環境情報の取得
- os:ファイル管理、ディレクトリ操作、パス処理、バッチリネーム
❓ よくある質問
Q
random は暗号学的に安全な乱数に適していますか?A いいえ。
random は PRNG(疑似乱数ジェネレータ)を使用しており、予測可能です。暗号学的に安全な乱数(パスワードやトークンの生成など)には、secrets モジュールを使用してください。Q
time.sleep() はプログラム全体をブロックします。非ブロッキングの遅延はどうすればよいですか?A
sleep() は現在のスレッドをブロックします。非ブロッキング遅延には、マルチスレッド化や asyncio のような非同期フレームワークを使用します。シンプルなシナリオでは sleep() で十分です。Q
os と pathlib はどちらを使うべきですか?A Python 3.4+ では
pathlib が推奨されます(よりオブジェクト指向で直感的)。ただし、os はより低レベルで包括的です。新しいプロジェクトでは pathlib を、低レベルのシステムコールには os を使用してください。📖 まとめ
random:randint()、choice()、sample()、shuffle()—— ランダム選択と生成time:time()タイムスタンプ、sleep()一時停止、strftime()フォーマットsys:argvコマンドライン引数、exit()プログラム終了os:ファイルパスチェック、ディレクトリ操作、ファイル名変更- これら 4 つのモジュールは Python 標準ライブラリの「スターターパック」であり、日常の開発で頻繁に使用されます
📝 練習問題
-
基本(難易度 ⭐):1 から 100 までのランダムな整数を 10 個生成し、それらとその平均を出力するプログラムを書いてください。
-
中級(難易度 ⭐⭐):パスワード生成関数
generate_password(length=8)を書いてください。大文字、小文字、数字を含むランダムなパスワードを作成します。ヒント:文字プールとしてstring.ascii_letters + string.digitsを使用し、random.choice()で文字を選びます。 -
挑戦(難易度 ⭐⭐⭐):「フォルダ統計ツール」を書いてください。ディレクトリパス(
sys.argvで渡される)が与えられたとき、ファイルタイプ(拡張子)ごとのファイル数と合計サイズをカウントします。ヒント:反復にos.listdir()、拡張子にos.path.splitext()、ファイルサイズにos.path.getsize()を使用。



