DiskReaderWriter.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import os
  2. from magic_pdf.io.AbsReaderWriter import AbsReaderWriter
  3. from loguru import logger
  4. MODE_TXT = "text"
  5. MODE_BIN = "binary"
  6. class DiskReaderWriter(AbsReaderWriter):
  7. def __init__(self, parent_path, encoding="utf-8"):
  8. self.path = parent_path
  9. self.encoding = encoding
  10. def read(self, path, mode=MODE_TXT):
  11. if os.path.isabs(path):
  12. abspath = path
  13. else:
  14. abspath = os.path.join(self.path, path)
  15. if not os.path.exists(abspath):
  16. logger.error(f"文件 {abspath} 不存在")
  17. raise Exception(f"文件 {abspath} 不存在")
  18. if mode == MODE_TXT:
  19. with open(abspath, "r", encoding=self.encoding) as f:
  20. return f.read()
  21. elif mode == MODE_BIN:
  22. with open(abspath, "rb") as f:
  23. return f.read()
  24. else:
  25. raise ValueError("Invalid mode. Use 'text' or 'binary'.")
  26. def write(self, content, path, mode=MODE_TXT):
  27. if os.path.isabs(path):
  28. abspath = path
  29. else:
  30. abspath = os.path.join(self.path, path)
  31. if mode == MODE_TXT:
  32. with open(abspath, "w", encoding=self.encoding) as f:
  33. f.write(content)
  34. logger.info(f"内容已成功写入 {abspath}")
  35. elif mode == MODE_BIN:
  36. with open(abspath, "wb") as f:
  37. f.write(content)
  38. logger.info(f"内容已成功写入 {abspath}")
  39. else:
  40. raise ValueError("Invalid mode. Use 'text' or 'binary'.")
  41. def read_jsonl(self, path: str, byte_start=0, byte_end=None, encoding="utf-8"):
  42. return self.read(path)
  43. # 使用示例
  44. if __name__ == "__main__":
  45. file_path = "io/example.txt"
  46. drw = DiskReaderWriter("D:\projects\papayfork\Magic-PDF\magic_pdf")
  47. # 写入内容到文件
  48. drw.write(b"Hello, World!", path="io/example.txt", mode="binary")
  49. # 从文件读取内容
  50. content = drw.read(path=file_path)
  51. if content:
  52. logger.info(f"从 {file_path} 读取的内容: {content}")