代码如下:
import os
def updateTxt(file,old_str,new_str):
"""
:param file:
:param old_str:
:param new_str:
:return:
"""
file_string=''
with open(file, 'r') as f:
for line in f:
line = line.replace(old_str,new_str)
file_string += line
with open(file, 'w') as f:
f.write(file_string)
updateTxt('a.txt', 'h2b', 'h2b.cc')
updateTxt('a.txt', '玩游戏', '不玩' )
注意中文编码问题(UnicodeDecodeError: 'gbk' codec can't decode byte 0x8f in position 95: illegal multibyte sequence)把txt文件改成gbk或者程序改成utf-8,本文改的是txt