DiskReaderWriter.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import os
  2. from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter
  3. from loguru import logger
  4. class DiskReaderWriter(AbsReaderWriter):
  5. def __init__(self, parent_path, encoding="utf-8"):
  6. self.path = parent_path
  7. self.encoding = encoding
  8. def read(self, path, mode=AbsReaderWriter.MODE_TXT):
  9. if os.path.isabs(path):
  10. abspath = path
  11. else:
  12. abspath = os.path.join(self.path, path)
  13. if not os.path.exists(abspath):
  14. logger.error(f"file {abspath} not exists")
  15. raise Exception(f"file {abspath} no exists")
  16. if mode == AbsReaderWriter.MODE_TXT:
  17. with open(abspath, "r", encoding=self.encoding) as f:
  18. return f.read()
  19. elif mode == AbsReaderWriter.MODE_BIN:
  20. with open(abspath, "rb") as f:
  21. return f.read()
  22. else:
  23. raise ValueError("Invalid mode. Use 'text' or 'binary'.")
  24. def write(self, content, path, mode=AbsReaderWriter.MODE_TXT):
  25. if os.path.isabs(path):
  26. abspath = path
  27. else:
  28. abspath = os.path.join(self.path, path)
  29. directory_path = os.path.dirname(abspath)
  30. if not os.path.exists(directory_path):
  31. os.makedirs(directory_path)
  32. if mode == AbsReaderWriter.MODE_TXT:
  33. with open(abspath, "w", encoding=self.encoding, errors="replace") as f:
  34. f.write(content)
  35. elif mode == AbsReaderWriter.MODE_BIN:
  36. with open(abspath, "wb") as f:
  37. f.write(content)
  38. else:
  39. raise ValueError("Invalid mode. Use 'text' or 'binary'.")
  40. def read_offset(self, path: str, offset=0, limit=None):
  41. abspath = path
  42. if not os.path.isabs(path):
  43. abspath = os.path.join(self.path, path)
  44. with open(abspath, "rb") as f:
  45. f.seek(offset)
  46. return f.read(limit)
  47. if __name__ == "__main__":
  48. if 0:
  49. file_path = "io/test/example.txt"
  50. drw = DiskReaderWriter("D:\projects\papayfork\Magic-PDF\magic_pdf")
  51. # 写入内容到文件
  52. drw.write(b"Hello, World!", path="io/test/example.txt", mode="binary")
  53. # 从文件读取内容
  54. content = drw.read(path=file_path)
  55. if content:
  56. logger.info(f"从 {file_path} 读取的内容: {content}")
  57. if 1:
  58. drw = DiskReaderWriter("/opt/data/pdf/resources/test/io/")
  59. content_bin = drw.read_offset("1.txt")
  60. assert content_bin == b"ABCD!"
  61. content_bin = drw.read_offset("1.txt", offset=1, limit=2)
  62. assert content_bin == b"BC"