你想将文件里面的所有'hello'字符串全部换成'nihao',而又不想创建临时文件,可以尝试如下方法:
import mmap
import contextlib
def modify_text_file(file,src,dst):
if len(src) != len(dst):
print ("Sorry,替换字符串的长度不一样,无法进行替换!")
return
with open("D:\\123.txt",'r+') as fp:
with contextlib.closing(mmap.mmap(fp.fileno(), 0,access=mmap.ACCESS_WRITE)) as mm:
mm.seek(0)
while True:
local = mm.find(src)
if local >= 0:
print (local)
mm[local:local+len(src)] = dst
else:
break
print ('替换完成!')
if __name__ == '__main__':
file = 'D:\\123.txt'
src = b'hello
dst = b'nihao'
modify_text_file(file,src,dst)
如果文件不太大,也可以使用正则替换:
import re
import mmap
import contextlib
def modify_text_file(file,src,dst):
if len(src) != len(dst):
print ("Sorry,替换字符串的长度不一样,无法进行替换!")
return
reg = re.compile(src,re.IGNORECASE)
with open("D:\\123.txt",'r+') as fp:
with contextlib.closing(mmap.mmap(fp.fileno(), 0,access=mmap.ACCESS_WRITE)) as mm:
mm.seek(0)
data = reg.sub(dst,mm)
mm.write(data)
print ('All OVER')
if __name__ == '__main__':
file = 'D:\\123.txt'
src = b'hello'
dst = b'nihao'
modify_text_file(file,src,dst)
欢迎关注本人微信公众号,会分享更多的干货: