from datetime import datetime
def make_backup_name(project_name, now=None):
now = now or datetime.now()
timestamp = now.strftime("%Y%m%d_%H%M%S")
return f"{project_name}_{timestamp}.zip"
print(make_backup_name("shuijing_usr"))
把 now 設成可傳入參數,測試時可固定時間,避免測試結果每秒不同。
三、先定義排除規則
from pathlib import Path
EXCLUDED_NAMES = {
".env",
"secrets.json",
"private_key.pem",
}
EXCLUDED_PARTS = {
"__pycache__",
".git",
"待授權原始媒體",
}
def should_exclude(path):
path = Path(path)
if path.name in EXCLUDED_NAMES:
return True
return any(part in EXCLUDED_PARTS for part in path.parts)
排除清單須依專案實際資料政策共同確認,不能假設所有叫「照片」或「逐字稿」的內容都有相同公開權限。
四、建立備份預覽清單
from pathlib import Path
def collect_backup_files(source):
source = Path(source).resolve()
if not source.is_dir():
raise NotADirectoryError(f"來源不是資料夾:{source}")
files = []
for path in sorted(source.rglob("*")):
relative = path.relative_to(source)
if path.is_file() and not should_exclude(relative):
files.append((path, relative))
return files
def preview_backup(files):
total_size = sum(path.stat().st_size for path, _ in files)
print("預計檔案數:", len(files))
print("預計位元組數:", total_size)
for _, relative in files:
print("-", relative)
from pathlib import Path, PurePosixPath
import zipfile
def validate_archive_names(zip_path):
with zipfile.ZipFile(zip_path, "r") as archive:
for name in archive.namelist():
member = PurePosixPath(name)
if member.is_absolute() or ".." in member.parts:
raise ValueError(f"不安全的ZIP路徑:{name}")
if member.parts and ":" in member.parts[0]:
raise ValueError(f"疑似磁碟路徑:{name}")
return True
十、還原到全新的隔離資料夾
from pathlib import Path
import zipfile
def restore_for_test(zip_path, target):
zip_path = Path(zip_path)
target = Path(target)
validate_archive_names(zip_path)
target.mkdir(parents=True, exist_ok=False)
target_root = target.resolve()
with zipfile.ZipFile(zip_path, "r") as archive:
for info in archive.infolist():
output = (target_root / info.filename).resolve()
if not output.is_relative_to(target_root):
raise ValueError(f"還原路徑越界:{info.filename}")
archive.extractall(target_root)
return target_root
from pathlib import Path
root = Path("shuijing_usr_demo")
print("第一層內容:")
for path in sorted(root.iterdir()):
print("-", path.name)
print("所有 CSV:")
for path in sorted(root.rglob("*.csv")):
print("-", path)
from pathlib import Path
def build_rename_plan(folder):
folder = Path(folder)
plan = []
for number, source in enumerate(
sorted(folder.glob("*.jpg")),
start=1,
):
target = source.with_name(f"活動照片_{number:03d}.jpg")
plan.append((source, target))
return plan
def show_plan(plan):
for source, target in plan:
print(f"預覽:{source.name} → {target.name}")
plan = build_rename_plan("shuijing_usr_demo/活動照片")
show_plan(plan)
十二、安全執行重新命名
def apply_rename_plan(plan, confirmed=False):
if not confirmed:
print("預覽模式:沒有變更任何檔案")
return
targets = [target for _, target in plan]
if len(targets) != len(set(targets)):
raise ValueError("計畫中有重複目標檔名")
for source, target in plan:
if not source.is_file():
raise FileNotFoundError(f"來源不存在:{source}")
if target.exists() and target != source:
raise FileExistsError(f"目標已存在:{target}")
for source, target in plan:
if source != target:
source.rename(target)
print(f"已重新命名:{source.name} → {target.name}")
apply_rename_plan(plan, confirmed=False)
from collections import Counter
from pathlib import Path
def inventory(folder):
folder = Path(folder)
files = [path for path in folder.rglob("*") if path.is_file()]
extensions = Counter(
path.suffix.lower() or "(無副檔名)" for path in files
)
return files, extensions
files, extensions = inventory("shuijing_usr_demo")
print("檔案總數:", len(files))
for extension, count in sorted(extensions.items()):
print(extension, count)
def print_tree(node, depth=0):
indent = " " * depth
print(f"{indent}• {node['名稱']}")
for child in node["子項目"]:
print_tree(child, depth + 1)
print_tree(cultural_tree)
當 子項目 是空串列時,for 不會執行,函式自然返回。這裡的空串列就是隱含的基底條件。
五、任務二:統計全部節點與導覽點
目前節點先算 1,再加上所有子樹的節點數。若只想統計沒有子項目的導覽點,遇到葉節點時回傳 1。
def count_nodes(node):
total = 1
for child in node["子項目"]:
total += count_nodes(child)
return total
def count_leaves(node):
if not node["子項目"]:
return 1
return sum(count_leaves(child) for child in node["子項目"])
print("全部節點:", count_nodes(cultural_tree))
print("導覽點:", count_leaves(cultural_tree))
def find_path(node, target, path=None):
if path is None:
path = []
current_path = path + [node["名稱"]]
if node["名稱"] == target:
return current_path
for child in node["子項目"]:
result = find_path(child, target, current_path)
if result is not None:
return result
return None
path = find_path(cultural_tree, "魚菜共生")
if path:
print(" → ".join(path))
else:
print("找不到指定導覽點")
七、把葉節點整理成導覽選單
def collect_routes(node, path=None):
if path is None:
path = []
current_path = path + [node["名稱"]]
if not node["子項目"]:
return [" → ".join(current_path)]
routes = []
for child in node["子項目"]:
routes.extend(collect_routes(child, current_path))
return routes
for number, route in enumerate(collect_routes(cultural_tree), start=1):
print(f"{number}. {route}")
八、遞迴不一定是唯一答案
情境
較適合
原因
樹狀資料、資料夾、巢狀選單
遞迴
程式結構貼近資料結構
固定範圍的重複工作
for/while
直觀且沒有遞迴深度問題
層數可能非常深
自行維護 stack 的迴圈
避免超過 Python 遞迴深度
以下以串列當作堆疊,完成相同的深度優先走訪:
def print_tree_iterative(root):
stack = [(root, 0)]
while stack:
node, depth = stack.pop()
print(f"{' ' * depth}• {node['名稱']}")
for child in reversed(node["子項目"]):
stack.append((child, depth + 1))
print_tree_iterative(cultural_tree)
records = [28.5, None, 29.1, None, 27.8]
for temperature in records:
if temperature is None:
print("本筆水溫缺漏,跳過計算。")
continue
print(f"有效水溫:{temperature:.1f}°C")
statuses = ["正常", "正常", "離線", "正常"]
for number, status in enumerate(statuses, start=1):
print(f"檢查第{number}座:{status}")
if status == "離線":
print("找到離線設備,停止本次搜尋。")
break