python替换文件内容
替换前文件内容
hellonicetomeetyou
hellonicetomeetyou
hellonicetomeetyou
hellonicetomeetyou
hellonicetomeetyou
hellonicetomeetyou
代码
"""
@File : MyReplace.py
@Contact : zhangyin@newlink.com
@Modify Time @Author @Version
------------ ------- --------
2022/1/26 11:40 上午 张胤 1.0
@Desciption:re.sub替换
将file_name里的hello替换成jack
"""
import os.path
import re
file_name = os.path.join(os.path.dirname(__file__), 'hello.txt')
with open(file_name, mode='r') as f:
readlines = f.readlines()
with open(file_name, mode='w') as f:
for line in readlines:
line_new = re.sub('hello', 'jack', line)
f.writelines(line_new)
替换后文件内容
jacknicetomeetyou
jacknicetomeetyou
jacknicetomeetyou
jacknicetomeetyou
jacknicetomeetyou
jacknicetomeetyou