python 修改文件内容函数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
以上是关于python 修改文件内容函数的主要内容,如果未能解决你的问题,请参考以下文章