码迷,mamicode.com
首页 > 编程语言 > 详细

python 修改文件内容函数

时间:2017-10-31 18:42:09      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:rda   默认   col   with open   txt   python   open   log   hang   

因为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 修改文件内容函数

标签:rda   默认   col   with open   txt   python   open   log   hang   

原文地址:http://www.cnblogs.com/ols888/p/7762554.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!