Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.7 KiB

  1. import os
  2. import shutil
  3. import zipfile
  4. class ZipProcessorInh:
  5. def __init__(self, zipname):
  6. self.zipname = zipname
  7. self.temp_directory = "unzipped-{}".format(self.zipname[:-4])
  8. def _full_filename(self, filename):
  9. return os.path.join(self.temp_directory, filename)
  10. def process_zip(self):
  11. self.unzip_files()
  12. self.process_files()
  13. self.zip_files()
  14. def unzip_files(self):
  15. os.mkdir(self.temp_directory)
  16. zip = zipfile.ZipFile(self.zipname)
  17. try:
  18. zip.extractall(self.temp_directory)
  19. finally:
  20. zip.close()
  21. def zip_files(self):
  22. file = zipfile.ZipFile(self.zipname, "w")
  23. for filename in os.listdir(self.temp_directory):
  24. file.write(self._full_filename(filename), filename)
  25. shutil.rmtree(self.temp_directory)
  26. class ZipProcessorComp:
  27. def __init__(self, zipname, processor):
  28. self.zipname = zipname
  29. self.temp_directory = "unzipped-{}".format(zipname[:-4])
  30. self.processor = processor
  31. def _full_filename(self, filename):
  32. return os.path.join(self.temp_directory, filename)
  33. def process_zip(self):
  34. self.unzip_files()
  35. self.processor.process(self)
  36. self.zip_files()
  37. def unzip_files(self):
  38. os.mkdir(self.temp_directory)
  39. zip = zipfile.ZipFile(self.zipname)
  40. try:
  41. zip.extractall(self.temp_directory)
  42. finally:
  43. zip.close()
  44. def zip_files(self):
  45. file = zipfile.ZipFile(self.zipname, "w")
  46. for filename in os.listdir(self.temp_directory):
  47. file.write(self._full_filename(filename), filename)
  48. shutil.rmtree(self.temp_directory)