_弧⑿薷脑募绞?
_ef alter(file,old_str,new_str):
?
?"""
_婊晃募械淖址?
?:param file:文件名
?:param old_str:就字符串
?:param new_str:新字符串
?:return:
?
?"""
_ile_data = ""
?
_ith open(file, "r", encoding="utf-8") as f:
?
_or line in f:
?
_f old_str in line:
?
_ine = line.replace(old_str,new_str)
?
_ile_data += line
?
_ith open(file,"w",encoding="utf-8") as f:
?
_.write(file_data)
?
_lter("file1", "09876", "python")
?
__言募谌莺鸵薷牡哪谌菪吹叫挛募薪写娲⒌姆绞?
?
?2.1 python字符串替换的方法,修改文件内容
?
_mport os
?
_ef alter(file,old_str,new_str):
?
?"""
?
_婊坏淖址吹揭桓鲂碌奈募校缓蠼募境挛募奈次募拿?
?
?:param file: 文件路径
?
?:param old_str: 需要替换的字符串
?
?:param new_str: 替换的字符串
?
?:return: None
?
?"""
?
_ith open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
?
_or line in f1:
?
_f old_str in line:
?
_ine = line.replace(old_str, new_str)
?
_2.write(line)
?
_s.remove(file)
?
_s.rename("%s.bak" % file, file)
?
_lter("file1", "python", "测试")
?
?2.2 python 使用正则表达式 替换文件内容 re.sub 方法替换
?
_mport re,os
?
_ef alter(file,old_str,new_str):
?
_ith open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
?
_or line in f1:
?
_2.write(re.sub(old_str,new_str,line))
?
_s.remove(file)
?
_s.rename("%s.bak" % file, file)
这样编写:fa=open("A.txt","r")
ta=fa.readlines()
fb=open("B.txt","r")
tb=fb.readlines()
tb[2:-9]=ta
fa.close()
fb.close()
fb=open("B.txt","w")
fb.writelines(tb)
fb.close()
读文件的模式有很多种不一一列举,r+表示打开一个文件用于读写。文件指针将会放在文件的开头。def readFile(path):
#R
with open(path,"r+") as f:
for line in f:
print(line)
f.close()
print("读文件完成")
path="D:\\tmp\\manim\\file\\1.txt"
readFile(path)
查找字符串位置,str.find(target) 返回起始点位置如果是-1则表示不存在
"123WWW".find("WWW")
文件指针偏移到指定位置
#文件路径,原字符串,要替换成的目标字符串
def replaceText(filePath,sourceText,targetText):
if(len(sourceText)!=len(targetText)):
raise Exception("原始字符串长度与目标字符串不符,容易覆盖有用信息", sourceText,targetText)
with open(filePath,'r+') as f:
line=f.readline()
index=0
# 遇到中间空行的可以自行观察并不是空字符串
while ( line!=""):
print(line)
# 本行内字符串所在位置
windex=line.find(sourceText)
if(windex!=-1):
print("windex={}".format(windex))
print("当前位置:{},替换内容起点:{}".format(f.tell(),index+windex))
f.seek(index+windex)
f.write(targetText)
# f.flush()
f.seek(index)
# 返回当前文件指针,应该是新一行的开始位置
index=f.tell()
line=f.readline()
f.close()
print("文件修改完毕")