timmy bu gisti düzenledi 10 months ago. Düzenlemeye git
Değişiklik yok
timmy bu gisti düzenledi 10 months ago. Düzenlemeye git
Değişiklik yok
timmy bu gisti düzenledi 10 months ago. Düzenlemeye git
Değişiklik yok
timmy bu gisti düzenledi 1 year ago. Düzenlemeye git
1 file changed, 35 insertions
data_handler.py(dosya oluşturuldu)
| @@ -0,0 +1,35 @@ | |||
| 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 | |
| 10 | + | ||
| 11 | + | @abstractmethod | |
| 12 | + | def write_data(self, path, data): | |
| 13 | + | pass | |
| 14 | + | ||
| 15 | + | ||
| 16 | + | # YAML 策略 | |
| 17 | + | class YamlHandler(DataHandlerStrategy): | |
| 18 | + | def read_data(self, path): | |
| 19 | + | with open(path, "r") as f: | |
| 20 | + | return yaml.safe_load(f) | |
| 21 | + | ||
| 22 | + | def write_data(self, path, data): | |
| 23 | + | with open(path, "w") as f: | |
| 24 | + | yaml.safe_dump(data, f) | |
| 25 | + | ||
| 26 | + | ||
| 27 | + | # JSON 策略 | |
| 28 | + | class JsonHandler(DataHandlerStrategy): | |
| 29 | + | def read_data(self, path): | |
| 30 | + | with open(path, "r") as f: | |
| 31 | + | return json.load(f) | |
| 32 | + | ||
| 33 | + | def write_data(self, path, data): | |
| 34 | + | with open(path, "w") as f: | |
| 35 | + | json.dump(data, f, ensure_ascii=False, indent=4) | |