020: class, objects and instance: 一个简单的例子,压缩文件中内容的替换
2016-01-27 22:20
441 查看
这个例子是对前面学习的知道的一个简单总结。
在设计类的时候,并非所有的类都是埋头干活的类,同时也需要有很多类似于管理的类,这样的类的功能就是调用其他的类来共同的完成任务。
在设计类的时候,并非所有的类都是埋头干活的类,同时也需要有很多类似于管理的类,这样的类的功能就是调用其他的类来共同的完成任务。
import sys import os import shutil import zipfile class ZipReplace(object): def __init__(self, file_name, search_string, replace_string): self.file_name = file_name self.search_string = search_string self.replace_string = replace_string self.temp_directory = "unzipped-{}".format(file_name) def __full_filename(self, file_name): return os.path.join(self.temp_directory, file_name) def zip_find_replace(self): self.unzip_files() self.find_replace() self.zip_files() def unzip_files(self): os.mkdir(self.temp_directory) zip = zipfile.ZipFile(self.file_name) try: zip.extractall(self.temp_directory) finally: zip.close() def find_replace(self): for file_name in os.listdir(self.temp_directory): with open(self.__full_filename(file_name)) as file: contents = file.read() contents = contents.replace(self.search_string, self.replace_string) with open(self.__full_filename(file_name), 'w') as file: file.write(contents) def zip_files(self): file = zipfile.ZipFile(self.file_name, 'w') for file_name in os.listdir(self.temp_directory): file.write(self.__full_filename(file_name), file_name) shutil.rmtree(self.temp_directory) zr = ZipReplace("test.zip", 'hello', 'hello world...') zr.zip_find_replace()
相关文章推荐
- Selenium2(java)页面对象模型(Page Object) 八
- Objective-C与JavaScript交互的那些事
- RemObjects SDK 9.0 Beta_CodeFirst
- Objective-C 通知
- Error: while loading shared libraries: libXXX.so.X: cannot open shared object file: No such file
- Objective-C 单例
- JSON对象中的JSONObject和JSONArray以及与Map、String、数组的转化
- Objective-C特性:Runtime
- org.hibernate.NonUniqueObjectException: a different object with the same identifier value was ...
- python object类
- 对 removeObject 的理解
- node之object-assign
- Android小问题:String转换Json,以及org.json.JSONObject与org.json.JSONArray相互添加
- JSONObject 类
- Could not find MessageBodyWriter for response object of type: application/json
- 理解 Objective-C Runtime
- iOS开发系列—Objective-C之Foundation框架
- MockObject
- JavaScript values and Objective-C objects
- Objective-C中的instancetype和id关键字