标签:
代码已经过测试
import re import mmap import os import shutil old_text=‘test‘ new_text=‘text‘ path=r‘C:\Users\Administrator\Desktop\2.txt‘ cpattern = re.compile(str(old_text)) with open(path,mode=‘rb‘) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = "".join(r_file) result= re.sub(cpattern, new_text, r_data) r_data.close() with open(path,mode=‘w‘) as w_file: w_file.write(result)
标签:
原文地址:http://www.cnblogs.com/slqt/p/5880794.html