---
title: "05 - 常用內建模組"
type: note
specialty: Programming
tags: [python, 05-常用模組]
---

# 05 - 常用內建模組

← [[04-函式]] | 下一篇 → [[06-速查表]]

---

## os — 檔案系統操作

```python
import os

os.getcwd()                    # 取得目前工作目錄
os.listdir(".")               # 列出目錄內容
os.path.exists("file.txt")    # 確認檔案是否存在
os.path.join("folder", "file.txt")   # 組合路徑（跨平台安全）
os.makedirs("new/folder", exist_ok=True)  # 建立資料夾
```

---

## math — 數學計算

```python
import math

math.sqrt(16)      # 4.0（開根號）
math.ceil(3.2)     # 4（無條件進位）
math.floor(3.8)    # 3（無條件捨去）
math.pi            # 3.14159...
math.log(100, 10)  # 2.0（log 以 10 為底）
```

---

## random — 隨機數

```python
import random

random.random()            # 0.0 到 1.0 的隨機浮點數
random.randint(1, 100)     # 1 到 100 的隨機整數
random.choice([1, 2, 3])   # 隨機選一個元素
random.shuffle([1, 2, 3])  # 隨機打亂（in-place）
random.sample([1,2,3,4,5], 3)  # 不重複抽取 3 個
```

---

## datetime — 日期時間

```python
from datetime import datetime, date, timedelta

now = datetime.now()
print(now)                    # 2026-04-22 12:34:56.789
print(now.strftime("%Y-%m-%d"))  # 2026-04-22

today = date.today()
yesterday = today - timedelta(days=1)

# 計算時間差
d1 = date(2026, 1, 1)
d2 = date(2026, 4, 22)
diff = d2 - d1
print(diff.days)    # 111
```

---

## json — JSON 處理

```python
import json

# dict → JSON 字串
data = {"name": "Andrew", "age": 28}
json_str = json.dumps(data, ensure_ascii=False, indent=2)

# JSON 字串 → dict
parsed = json.loads(json_str)

# 讀寫 JSON 檔案
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)
```

---

## 安裝第三方套件（pip）

```bash
# 安裝套件
pip install requests

# 查看已安裝套件
pip list

# 產生 requirements.txt（記錄相依套件）
pip freeze > requirements.txt

# 從 requirements.txt 安裝
pip install -r requirements.txt
```

### 常用第三方套件

| 套件 | 用途 |
|------|------|
| `requests` | HTTP 請求（爬蟲、API） |
| `pandas` | 資料分析 |
| `numpy` | 數值計算 |
| `matplotlib` | 資料視覺化 |
| `flask` | 輕量 Web 框架 |
| `selenium` | 瀏覽器自動化 |

---

← [[04-函式]] | 下一篇 → [[06-速查表]]
