ITPub博客

首页 > 应用开发 > IT综合 > python备份文件及写入新内容

python备份文件及写入新内容

原创 IT综合 作者:5功啊 时间:2017-02-07 17:36:22 0 删除 编辑
 def oper_file(file_name,lines): ##备份旧文件,将更改的内容写入新文件  old_file=file_name
    now = datetime.datetime.now().strftime("%Y%m%d%H%M")
    newfile=old_file+"_bk_"+now
    shutil.copyfile(old_file,newfile)
    new_conf = open(file_name, 'w+')
    new_conf.writelines(lines)
    new_conf.flush()
    new_conf.close()

该函数调用了shutil和datetime模块。
首先确定备份文件的名字,然后通过shutil.copyfile()备份文件。
然后通过open()以“w+”模式打开文件,将新内容写入文件。



来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/26735168/viewspace-2133185/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: re模块
请登录后发表评论 登录
全部评论

注册时间:2016-07-07

  • 博文量
    38
  • 访问量
    32421