Python

標準ライブラリ

Python

pathlib・datetime・json・os・re・typing

pathlib / os

ファイルシステム操作

pathlib_examples.py python
from pathlib import Path

# パスの構築
p = Path('/home/user/docs/report.txt')
p = Path.home() / 'docs' / 'report.txt'  # /演算子で結合
p = Path('.')   # カレントディレクトリ

# パス情報
p.name          # 'report.txt'
p.stem          # 'report'
p.suffix        # '.txt'
p.suffixes      # ['.txt']
p.parent        # Path('/home/user/docs')
p.parts         # ('/', 'home', 'user', 'docs', 'report.txt')
p.is_absolute() # True
p.exists()      # ファイル存在確認
p.is_file()     # ファイルかどうか
p.is_dir()      # ディレクトリかどうか

# ファイルの読み書き
text = p.read_text(encoding='utf-8')
p.write_text('hello', encoding='utf-8')
bytes_data = p.read_bytes()
p.write_bytes(b'\x00\x01')

# ディレクトリ操作
p.mkdir(parents=True, exist_ok=True)   # 作成
p.unlink()                             # ファイル削除
p.rmdir()                              # 空ディレクトリ削除
p.rename(p.parent / 'new_name.txt')   # リネーム
p.replace(dest)                        # 移動・上書き

# ファイル一覧
for f in Path('.').iterdir(): print(f)
for f in Path('.').glob('*.py'): print(f)     # パターン
for f in Path('.').rglob('*.py'): print(f)    # 再帰

# ファイル情報
stat = p.stat()
stat.st_size    # バイトサイズ
stat.st_mtime   # 更新時刻(Unix時間)

datetime / json

日時処理とJSONシリアライズ

datetime_json.py python
from datetime import datetime, date, timedelta, timezone

# 現在時刻
now_local = datetime.now()                   # ローカル時刻(非推奨)
now_utc   = datetime.now(timezone.utc)       # UTC(推奨)
now_jst   = datetime.now(timezone(timedelta(hours=9)))  # JST

# 作成
dt = datetime(2025, 10, 24, 14, 30, 0, tzinfo=timezone.utc)
d  = date(2025, 10, 24)

# フォーマット・パース
formatted = dt.strftime('%Y-%m-%d %H:%M:%S')
parsed    = datetime.strptime('2025-10-24', '%Y-%m-%d')
iso_str   = dt.isoformat()                   # '2025-10-24T14:30:00+00:00'
parsed2   = datetime.fromisoformat(iso_str)

# 演算
tomorrow  = dt + timedelta(days=1)
last_week = dt - timedelta(weeks=1)
diff      = dt - datetime(2025, 1, 1, tzinfo=timezone.utc)
diff.days, diff.seconds  # 日数と秒数

# JSON
import json

data = {'name': 'Alice', 'scores': [95, 87, 92], 'active': True}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
parsed   = json.loads(json_str)

# ファイルへの読み書き
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)
with open('data.json', encoding='utf-8') as f:
    data = json.load(f)

# カスタムシリアライザー
class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime): return obj.isoformat()
        return super().default(obj)

json.dumps({'dt': datetime.now(timezone.utc)}, cls=DateEncoder)

typing / re

型ヒントと正規表現

typing_re.py python
# === typing ===
from typing import (
    Any, Union, Optional, Literal, Final,
    TypeVar, Generic, Protocol,
    Callable, Iterator, Generator,
    TypedDict, overload,
)

# TypedDict
class UserDict(TypedDict):
    id:   int
    name: str
    email: str

# Protocol(構造的サブタイプ)
class Drawable(Protocol):
    def draw(self) -> None: ...

def render(shape: Drawable) -> None:  # Duck typing を型安全に
    shape.draw()

# TypeVar(ジェネリクス)
T = TypeVar('T')
def first(lst: list[T]) -> T | None:
    return lst[0] if lst else None

# Literal型
Mode = Literal['r', 'w', 'a', 'rb', 'wb']
def open_file(path: str, mode: Mode) -> ...: ...

# === re(正規表現)===
import re

text = 'Alice: alice@example.com, Bob: bob@test.org'

# 基本操作
re.match(r'^\d+', text)           # 先頭マッチのみ
re.search(r'\w+@\w+\.\w+', text)  # 最初の1つ
re.findall(r'[\w.]+@[\w.]+', text) # 全てリスト
re.sub(r'\d+', 'N', 'a1b2c3')     # 'aNbNcN'

# グループ
m = re.search(r'(\w+)@(\w+)\.(\w+)', text)
m.group(0)   # 'alice@example.com'(全体)
m.group(1)   # 'alice'(1番目のグループ)
m.groups()   # ('alice', 'example', 'com')

# 名前付きグループ
m = re.search(r'(?P<user>\w+)@(?P<domain>[\w.]+)', text)
m.group('user')    # 'alice'
m.groupdict()      # {'user': 'alice', 'domain': 'example.com'}

# コンパイル(繰り返し使う場合)
EMAIL_RE = re.compile(r'[\w.+-]+@[\w-]+\.[\w.]+')
EMAIL_RE.findall(text)