Browse Source

refactoring of zipsearch.py by using inhiterance

master
T. Meissner 10 years ago
parent
commit
b0a6f0240f
2 changed files with 56 additions and 0 deletions
  1. +32
    -0
      python_3_oop/chapter05/zipprocessor.py
  2. +24
    -0
      python_3_oop/chapter05/zipreplace.py

+ 32
- 0
python_3_oop/chapter05/zipprocessor.py View File

@ -0,0 +1,32 @@
import os
import shutil
import zipfile
class ZipProcessor:
def __init__(self, zipname):
self.zipname = zipname
self.temp_directory = "unzipped-{}".format(self.zipname[:-4])
def _full_filename(self, filename):
return os.path.join(self.temp_directory, filename)
def process_zip(self):
self.unzip_files()
self.process_files()
self.zip_files()
def unzip_files(self):
os.mkdir(self.temp_directory)
zip = zipfile.ZipFile(self.zipname)
try:
zip.extractall(self.temp_directory)
finally:
zip.close()
def zip_files(self):
file = zipfile.ZipFile(self.zipname, "w")
for filename in os.listdir(self.temp_directory):
file.write(self._full_filename(filename), filename)
shutil.rmtree(self.temp_directory)

+ 24
- 0
python_3_oop/chapter05/zipreplace.py View File

@ -0,0 +1,24 @@
from zipprocessor import ZipProcessor
import sys
import os
class ZipReplace(ZipProcessor):
def __init__(self, filename, search_string, replace_string):
super().__init__(filename)
self.search_string = search_string
self.replace_string = replace_string
def process_files(self):
'''perform a search and replace on all files in the temporrary
directory'''
for filename in os.listdir(self.temp_directory):
with open(self._full_filename(filename)) as file:
contents = file.read()
contents = contents.replace(self.search_string, self.replace_string)
with open(self._full_filename(filename), "w") as file:
file.write(contents)
if __name__ == "__main__":
ZipReplace(*sys.argv[1:4]).process_zip()

Loading…
Cancel
Save