DiskReaderWriter.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import os
  2. from magic_pdf.rw.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. directory_path = os.path.dirname(abspath)
  32. if not os.path.exists(directory_path):
  33. os.makedirs(directory_path)
  34. if mode == MODE_TXT:
  35. with open(abspath, "w", encoding=self.encoding) as f:
  36. f.write(content)
  37. elif mode == MODE_BIN:
  38. with open(abspath, "wb") as f:
  39. f.write(content)
  40. else:
  41. raise ValueError("Invalid mode. Use 'text' or 'binary'.")
  42. def read_jsonl(self, path: str, byte_start=0, byte_end=None, encoding="utf-8"):
  43. return self.read(path)
  44. # 使用示例
  45. if __name__ == "__main__":
  46. file_path = "io/test/example.txt"
  47. drw = DiskReaderWriter("D:\projects\papayfork\Magic-PDF\magic_pdf")
  48. # 写入内容到文件
  49. drw.write(b"Hello, World!", path="io/test/example.txt", mode="binary")
  50. # 从文件读取内容
  51. content = drw.read(path=file_path)
  52. if content:
  53. logger.info(f"从 {file_path} 读取的内容: {content}")