Python 文件内容修改替换操作


Python 文件内容修改替换操作

1
2
3
4
5
6
7
8
9
10
11
import io

def alter_file(file,old_str,new_str):
file_data = ""
with io.open(file, "r", encoding="utf-8") as f:
for line in f:
if old_str in line:
line = line.replace(old_str,new_str)
file_data += line
with io.open(file,"w",encoding="utf-8") as f:
f.write(file_data)

使用

1
alter_file('index.html','{#channel}',channel)