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.

47 lines
1.4 KiB

  1. import sys
  2. import os
  3. import shutil
  4. import zipfile
  5. class ZipReplace:
  6. def __init__(self, filename, search_string, replace_string):
  7. self.filename = filename
  8. self.search_string = search_string
  9. self.replace_string = replace_string
  10. self.temp_directory = "unzipped-{}".format(filename)
  11. def _full_filename(self, filename):
  12. return os.path.join(self.temp_directory, filename)
  13. def zip_find_replace(self):
  14. self.unzip_files()
  15. self.find_replace()
  16. self.zip_files()
  17. def unzip_files(self):
  18. os.mkdir(self.temp_directory)
  19. zip = zipfile.ZipFile(self.filename)
  20. try:
  21. zip.extractall(self.temp_directory)
  22. finally:
  23. zip.close()
  24. def find_replace(self):
  25. for filename in os.listdir(self.temp_directory):
  26. with open(self._full_filename(filename)) as file:
  27. contents = file.read()
  28. contents = contents.replace(self.search_string, self.replace_string)
  29. with open(self._full_filename(filename), "w") as file:
  30. file.write(contents)
  31. def zip_files(self):
  32. file = zipfile.ZipFile(self.filename, "w")
  33. for filename in os.listdir(self.temp_directory):
  34. file.write(self._full_filename(filename), filename)
  35. shutil.rmtree(self.temp_directory)
  36. if __name__ == "__main__":
  37. ZipReplace(*sys.argv[1:4]).zip_find_replace()