← 返回大綱
第九章

標準函式庫
應用

Standard Library Applications

os 模組

os — 作業系統操作

import os

# 目前工作目錄
print(os.getcwd())              # /Users/ian/project

# 列出目錄內容
print(os.listdir("."))          # ['main.py', 'data.txt']

# 建立 / 刪除目錄
os.makedirs("output", exist_ok=True)
# os.rmdir("output")

# 路徑操作
path = os.path.join("data", "users.json")  # data/users.json
print(os.path.exists(path))     # True / False
print(os.path.basename(path))   # users.json
print(os.path.dirname(path))    # data
datetime 模組

datetime — 日期與時間

from datetime import datetime, timedelta, date

now = datetime.now()
print(now)                          # 2026-05-06 10:30:00
print(now.strftime("%Y年%m月%d日")) # 2026年05月06日

# 時間計算
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)

# 計算兩個日期的差距
birthday = date(2000, 1, 1)
today = date.today()
delta = today - birthday
print(f"已出生 {delta.days} 天")
collections 模組

collections — 進階資料結構

from collections import Counter, defaultdict, deque

# Counter — 計數
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
count = Counter(words)
print(count)               # Counter({'apple': 3, 'banana': 2, ...})
print(count.most_common(2)) # [('apple', 3), ('banana', 2)]

# defaultdict — 有預設值的字典
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
print(dd["fruits"])   # ['apple', 'banana']
print(dd["empty"])    # [](不會 KeyError)
re 模組

re — 正規表達式

import re

text = "聯絡電話:0912-345-678,或 02-1234-5678"

# 搜尋
match = re.search(r"\d{4}-\d{4}", text)
if match:
    print(match.group())   # 1234-5678

# 找出所有符合
phones = re.findall(r"\d+-\d+-\d+", text)
print(phones)   # ['0912-345-678', '02-1234-5678']

# 替換
result = re.sub(r"\d{4}", "XXXX", "卡號:1234-5678")
print(result)   # 卡號:XXXX-XXXX
常用正規表達式

\d 數字  |  \w 字母數字  |  \s 空白  |  + 一個以上  |  * 零個以上

itertools 模組

itertools — 迭代工具

from itertools import product, combinations, permutations, chain

# 笛卡爾積
for r, g in product([1,2], ["A","B"]):
    print(r, g)   # (1,A) (1,B) (2,A) (2,B)

# 組合(不重複)
for c in combinations([1,2,3], 2):
    print(c)   # (1,2) (1,3) (2,3)

# 排列
for p in permutations([1,2,3], 2):
    print(p)   # (1,2) (1,3) (2,1) (2,3) (3,1) (3,2)

# 串接多個迭代器
for x in chain([1,2], [3,4], [5]):
    print(x)   # 1 2 3 4 5
pathlib 模組

pathlib — 現代路徑操作

from pathlib import Path

# 建立路徑(跨平台)
p = Path("data") / "users.json"
print(p)           # data/users.json

# 常用操作
print(p.exists())       # 是否存在
print(p.suffix)         # .json
print(p.stem)           # users
print(p.parent)         # data

# 遍歷目錄
for f in Path(".").glob("*.py"):
    print(f.name)

# 讀寫(更方便的語法)
text = Path("README.md").read_text(encoding="utf-8")
Path("output.txt").write_text("Hello", encoding="utf-8")
實作練習

動手試試看

import os
from datetime import datetime
from collections import Counter

# 分析一個文字檔案
def analyze_file(filename):
    try:
        text = open(filename, encoding="utf-8").read()
    except FileNotFoundError:
        print(f"找不到檔案:{filename}")
        return

    words = text.lower().split()
    counter = Counter(words)

    print(f"檔案:{filename}")
    print(f"字數:{len(words)}")
    print(f"不重複單字:{len(counter)}")
    print("最常出現的 5 個字:")
    for word, count in counter.most_common(5):
        print(f"  {word}: {count} 次")

analyze_file("README.md")

第九章完成!

學會了 os、datetime、collections、re、pathlib 等常用標準函式庫。