io_handler.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. """
  2. 文件I/O处理器模块
  3. 提供统一的文件读写接口,支持多种文件格式
  4. """
  5. import asyncio
  6. import aiofiles
  7. import json
  8. import os
  9. import re
  10. from pathlib import Path
  11. from typing import Any
  12. class FileIOHandler:
  13. """
  14. 文件I/O处理器:统一管理文件的读写
  15. 提供JSON和纯文本的读写功能,可扩展支持其他格式
  16. 使用示例:
  17. >>> handler = FileIOHandler()
  18. >>> data = handler.read_json("input.json")
  19. >>> handler.write_json(data, "output.json")
  20. """
  21. @staticmethod
  22. def string_to_json(data: str) -> Any:
  23. """
  24. 将字符串转换为JSON
  25. """
  26. try:
  27. json_data = re.sub(r'^```json|\n```$', '', data, flags=re.MULTILINE).strip()
  28. if not json_data:
  29. json_data = data
  30. return json.loads(json_data)
  31. except Exception as e:
  32. raise e
  33. @staticmethod
  34. def read_json(file_path: str) -> Any:
  35. """
  36. 读取JSON文件
  37. Args:
  38. file_path: 文件路径
  39. Returns:
  40. 解析后的JSON数据
  41. Raises:
  42. FileNotFoundError: 文件不存在
  43. json.JSONDecodeError: JSON解析错误
  44. """
  45. if not os.path.exists(file_path):
  46. raise FileNotFoundError(f"文件不存在: {file_path}")
  47. with open(file_path, 'r', encoding='utf-8') as f:
  48. return json.load(f)
  49. @staticmethod
  50. def write_json(data: Any, file_path: str, indent: int = 2):
  51. """
  52. 保存JSON文件
  53. Args:
  54. data: 要保存的数据
  55. file_path: 文件路径
  56. indent: JSON缩进空格数
  57. """
  58. output_path = Path(file_path)
  59. output_path.parent.mkdir(parents=True, exist_ok=True)
  60. # 如果数据是字符串,则先转换为JSON
  61. if isinstance(data, str):
  62. data = FileIOHandler.string_to_json(data)
  63. with open(output_path, 'w', encoding='utf-8') as f:
  64. json.dump(data, f, ensure_ascii=False, indent=indent)
  65. @staticmethod
  66. async def write_json_async(data: Any, file_path: str, indent: int = 2):
  67. """
  68. 异步保存JSON文件
  69. Args:
  70. data: 要保存的数据
  71. file_path: 文件路径
  72. indent: JSON缩进空格数
  73. """
  74. output_path = Path(file_path)
  75. output_path.parent.mkdir(parents=True, exist_ok=True)
  76. async with aiofiles.open(output_path, 'w', encoding='utf-8') as f:
  77. await f.write(json.dumps(data, ensure_ascii=False, indent=indent))
  78. @staticmethod
  79. def read_text(file_path: str) -> str:
  80. """
  81. 读取文本文件
  82. Args:
  83. file_path: 文件路径
  84. Returns:
  85. 文件内容字符串
  86. Raises:
  87. FileNotFoundError: 文件不存在
  88. """
  89. if not os.path.exists(file_path):
  90. raise FileNotFoundError(f"文件不存在: {file_path}")
  91. with open(file_path, 'r', encoding='utf-8') as f:
  92. return f.read()
  93. @staticmethod
  94. def write_text(content: str, file_path: str):
  95. """
  96. 保存文本文件
  97. Args:
  98. content: 要保存的内容
  99. file_path: 文件路径
  100. """
  101. output_path = Path(file_path)
  102. output_path.parent.mkdir(parents=True, exist_ok=True)
  103. with open(file_path, 'w', encoding='utf-8') as f:
  104. f.write(content)
  105. @staticmethod
  106. async def write_text_async(content: str, file_path: str):
  107. """
  108. 异步保存文本文件
  109. Args:
  110. content: 要保存的内容
  111. file_path: 文件路径
  112. """
  113. output_path = Path(file_path)
  114. output_path.parent.mkdir(parents=True, exist_ok=True)
  115. async with aiofiles.open(output_path, 'w', encoding='utf-8') as f:
  116. await f.write(content)
  117. @staticmethod
  118. def file_exists(file_path: str) -> bool:
  119. """
  120. 检查文件是否存在
  121. Args:
  122. file_path: 文件路径
  123. Returns:
  124. bool: 文件是否存在
  125. """
  126. return os.path.exists(file_path)