• 利用python备份文件夹


    以前写过一个非常白痴的备份脚本,就是将着整个我文件夹都拷贝到u盘里,每次拷贝前都将已经存在的文件夹删除掉。这样的话程序就很傻瓜代码也很少

    1 import os
    2 
    3 def backup(from_path,to_path):
    4     if os.path.exists(to_path):
    5         os.system('rm -rf to_path')
    6     os.system('cp from_path to_path')

    今天在python cookbook上看到一段代码,这段代码也是利用python进行备份文件夹,但是它的程序要聪明一点,只拷贝那些还未被备份的文件

     1 import os,sys,shutil,filecmp
     2 
     3 #def backup(path,backdirname = 'back'):
     4 #    for dir,subdir,files in os.walk(path):
     5 #        if backdirname not in subdir:
     6 #            backdir = os.path.join(dir,backdirname)
     7 #            os.mkdir(backdir)
     8 #        subdir[:] = [d for d in subdir if d !=backname]
     9 #        for file in files:
    10 #            filepath = os.path.join(dir,file)
    11 #            for index in xrange(100):
    12 #                backfile = '%s.%2.2%d'%(file,index)
    13 #                backpath = os.path.join(dir,backfile)
    14 #                if os.path.exists(backpath):break
    15 #            if index>0:
    16 #                old_backpath
    17 
    18 def backup(path,backdir_name='backdir'):
    19     MAXVERSIONS = 100
    20     for dir,subdir,files in os.walk(path):
    21         backdir = os.path.join(dir,backdir_name)
    22         if not os.path.exists(backdir):
    23             os.mkdir(backdir)
    24 
    25         subdir[:] = [d for d in subdir if d != backdir_name]
    26         for file in files:
    27             filepath = os.path.join(dir,file)
    28             backpath = os.path.join(backdir,file)
    29 
    30             for index in xrange(MAXVERSIONS):
    31                 backfile_name = '%s.%2.2d'%(backpath,index)
    32                 if not os.path.exists(backfile_name):break
    33 
    34 
    35             if index>0:
    36                 old_backup = '%s.%2.2d'%(backpath,index-1)
    37                 abspath = os.path.abspath(filepath)
    38                 try:
    39                     if os.path.isfile(abspath) and filecmp.cmp(old_backup,abspath,shallow = False):
    40                         continue
    41                 except OSError:
    42                     pass
    43                 
    44             try:
    45                 shutil.copy(filepath,backfile_name)
    46             except OSError:
    47                 pass
    48 if __name__ == '__main__':
    49     path = raw_input('please input the backup dir:')
    50     backup(path)
  • 相关阅读:
    Flex 布局教程:语法篇
    一些不错的滚动条
    SharePoint缓存导致访问慢解决
    针对SharePointFarm场时安装部署OWA的步骤
    【转】必需知道的 SharePoint 权限 Tips
    【转】SharePoint工作流中常用的方法
    通过SPList Definition自定义ListItem打开编辑详细页面
    Jquery 实现Xml文件内容处理
    【转】为 XmlNode.SelectNodes 加上排序功能
    [MSDN]关键字查询语言 (KQL) 语法参考
  • 原文地址:https://www.cnblogs.com/lianwl/p/3253103.html
Copyright © 2020-2023  润新知