All gists matching topic file-handling

timmy / 快速移動檔案到資料夾

0 gustos
0 bifurcaciones
1 archivos
Última actividad 7 months ago
一行指令搞定:把當前目錄的檔案移動到 archive 文件夾。
1 mkdir archive
2
3 find . -maxdepth 1 -type f -exec mv {} archive/ \;

timmy / 使用 contextmanager 建立自訂上下文管理器

0 gustos
0 bifurcaciones
3 archivos
Última actividad 9 months ago
contextlib.contextmanager 可用於建立自訂的 with 語句上下文管理器,適用於 資源管理(如檔案、資料庫連線、鎖定機制),確保進入與退出時執行適當的操作。
1 from contextlib import contextmanager
2
3 @contextmanager
4 def custom_context(name):
5 print(f"進入上下文: {name}")
6 try:
7 yield name # 提供資源
8 finally:
9 print(f"退出上下文: {name}")

timmy / 策略模式實作 YAML 與 JSON 資料處理

0 gustos
0 bifurcaciones
1 archivos
Última actividad 10 months ago
這段 Python 程式碼使用 策略模式(Strategy Pattern),定義一個 DataHandlerStrategy 介面,並實作 YAML (YamlHandler) 與 JSON (JsonHandler) 兩種不同的資料處理策略。它提供統一的 read_data 和 write_data 方法,讓程式可以根據不同的檔案格式 靈活讀取與寫入 YAML 或 JSON 檔案,適用於 配置管理、資料序列化或跨格式資料處理應用。
1 import yaml
2 import json
3 from abc import ABC, abstractmethod
4
5 # 策略介面
6 class DataHandlerStrategy(ABC):
7 @abstractmethod
8 def read_data(self, path):
9 pass
Siguiente Anterior