python修改文件内容

时间:2021-08-08 00:57:12
 1 def alter(file,old_str,new_str):
2 """
3 替换文件中的字符串
4 :param file:文件名
5 :param old_str:旧字符串
6 :param new_str:新字符串
7 :return:
8 """
9 file_data = ""
10 with open(file, "r", encoding="utf-8") as f:
11 for line in f:
12 if old_str in line:
13 line = line.replace(old_str,new_str)#line = line.replace(line,new_str)替换整行
14 file_data += line#写入file_data
15 with open(file,"w",encoding="utf-8") as f:
16 f.write(file_data)#写入文件
17
18 alter("file1", "<html>", "python")