python 修改文件内容函数
因为python自带库中没有修改文件内容的方法,自己写了两个修改文件内容的函数
import os def change_file(address,line,content): #修改文件指定行 f=open(address,"r",encoding="utf-8") f2=open("temporary_file.txt","w",encoding="utf-8") i=0 for v in f: i+=1 if i==line: f2.write(content) else: f2.write(v) f.close() f2.close() f = open(address, "w" ,encoding="utf-8") f2=open("temporary_file.txt", "r",encoding="utf-8") for v in f2: f.write(v) f.close() f2.close() change_file("yesterday.txt",1,"ols li\n") def file_replace(address,find_str,replace_str,replacenum=1): #替换文件指定词,默认替换一次, with open(address,"r",encoding="utf-8") as f,\ open("temporary_file.txt", "w", encoding="utf-8") as f2: if replacenum <=0: return 0 else: for v in f: if replacenum == 0: f2.write(v) else: if replacenum <= v.count(find_str): f2.write(v.replace(find_str, replace_str, replacenum)) replacenum = 0 else: f2.write(v.replace(find_str, replace_str)) replacenum = replacenum - v.count(find_str) f = open(address, "w" ,encoding="utf-8") f2=open("temporary_file.txt", "r",encoding="utf-8") for v in f2: f.write(v) f.close() f2.close() file_replace("yesterday.txt","昨日","今天",2)