ZipStream.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import io
  2. import os
  3. import zipfile
  4. class ZipStream(object):
  5. def __init__(self, dir_path):
  6. self.dir_path = dir_path
  7. self.pos = 0
  8. self.buff_pos = 0
  9. self.zf = zipfile.ZipFile(self, 'w', zipfile.ZIP_DEFLATED, allowZip64=True)
  10. self.buff = io.BytesIO()
  11. self.file_list = self.getFileList()
  12. def getFileList(self):
  13. for root, dirs, files in os.walk(self.dir_path):
  14. for file in files:
  15. file_path = root + "/" + file
  16. relative_path = os.path.join(os.path.relpath(root, self.dir_path), file)
  17. yield file_path, relative_path
  18. self.zf.close()
  19. def read(self, size=60 * 1024):
  20. for file_path, relative_path in self.file_list:
  21. self.zf.write(file_path, relative_path)
  22. if self.buff.tell() >= size:
  23. break
  24. self.buff.seek(0)
  25. back = self.buff.read()
  26. self.buff.truncate(0)
  27. self.buff.seek(0)
  28. self.buff_pos += len(back)
  29. return back
  30. def write(self, data):
  31. self.pos += len(data)
  32. self.buff.write(data)
  33. def tell(self):
  34. return self.pos
  35. def seek(self, pos, whence=0):
  36. if pos >= self.buff_pos:
  37. self.buff.seek(pos - self.buff_pos, whence)
  38. self.pos = pos
  39. def flush(self):
  40. pass
  41. if __name__ == "__main__":
  42. zs = ZipStream(".")
  43. out = open("out.zip", "wb")
  44. while 1:
  45. data = zs.read()
  46. print("Write %s" % len(data))
  47. if not data:
  48. break
  49. out.write(data)
  50. out.close()