serialization.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """序列化工具"""
  2. import json
  3. import pickle
  4. from typing import Any, Union
  5. from pathlib import Path
  6. def serialize_object(obj: Any, format: str = "json") -> Union[str, bytes]:
  7. """
  8. 序列化对象
  9. Args:
  10. obj: 要序列化的对象
  11. format: 序列化格式 ("json" 或 "pickle")
  12. Returns:
  13. 序列化后的数据
  14. """
  15. if format == "json":
  16. return json.dumps(obj, ensure_ascii=False, indent=2)
  17. elif format == "pickle":
  18. return pickle.dumps(obj)
  19. else:
  20. raise ValueError(f"不支持的序列化格式: {format}")
  21. def deserialize_object(data: Union[str, bytes], format: str = "json") -> Any:
  22. """
  23. 反序列化对象
  24. Args:
  25. data: 序列化的数据
  26. format: 序列化格式
  27. Returns:
  28. 反序列化后的对象
  29. """
  30. if format == "json":
  31. return json.loads(data)
  32. elif format == "pickle":
  33. return pickle.loads(data)
  34. else:
  35. raise ValueError(f"不支持的反序列化格式: {format}")
  36. def save_to_file(obj: Any, filepath: Union[str, Path], format: str = "json") -> None:
  37. """保存对象到文件"""
  38. filepath = Path(filepath)
  39. data = serialize_object(obj, format)
  40. mode = "w" if format == "json" else "wb"
  41. with open(filepath, mode) as f:
  42. f.write(data)
  43. def load_from_file(filepath: Union[str, Path], format: str = "json") -> Any:
  44. """从文件加载对象"""
  45. filepath = Path(filepath)
  46. mode = "r" if format == "json" else "rb"
  47. with open(filepath, mode) as f:
  48. data = f.read()
  49. return deserialize_object(data, format)