Python修改文件内容

时间:2022-03-10 02:58:08

工作中要写个脚本来修改文件的内容,然后就写了一个刷子:


#coding:utf8
import os 


def modify_file(old_file, new_version, old_version="https"):
    """
             修改文件内容
    """
    if os.path.isfile(old_file):
        try:
            new_file = "%s.bak" % old_file
            temp = file(new_file, "wb")   
            with open(old_file, "rb") as f:
                for line in f.readlines():
                    temp.write(line.replace(old_version, new_version))
            temp.close()
            os.remove(old_file)
            os.rename(new_file, old_file)
        except Exception,e:
            print e.message
        return True
    else:
        return False

              
def file_list(new_version):
    """
            获取文件列表
    """
    filelist = ["D:\当前版本号.txt", "D:\当前版本号.py", r"D:\D盘\version.ini"]
    try:
        for f in filelist:
            modify_file(f.decode("utf8"), new_version)
        print "修改完成!"
    except Exception,e:
        print e.message
        
             
if __name__ == "__main__":
    new_version = "ftp" 
    file_list(new_version)