python修改文件内容的3种方法详解

一个博客写的:

https://www.jb51.net/article/174303.htm

自己修改的一个方法:

#更新学校名称
#不能用这个setattr(NewSchoolDatas,"school_name",getattr(NewSchoolDatas,"school_name")+"p")
#使用setattr并不能修改py文件里面的值,它修改的是内存中的值
def updata_school_name(self,file, old_str, new_str): #记得方法里面写的时候加self,TypeError: updata_school_name() takes 3 positional arguments but 4 were given
"""
替换文件中的字符串
:param file:文件名
:param old_str:旧字符串
:param new_str:新字符串
:return:
"""
file_data = ""
with open(file, "r", encoding="utf-8") as f:
for line in f: #循环读取每一行
if "school_name="+ '"'+ old_str + '"' in line: #为防止替换出错,我是整行读取匹配,然后仅仅替换学校名字
line = line.replace(old_str, new_str)
file_data += line #要和上面的if对齐
with open(file, "w", encoding="utf-8") as f:
f.write(file_data)
原文地址:https://www.cnblogs.com/meblogs-08/p/13587362.html