Python特定文件备份方法源码示例,,Python备份文件的方


Python备份文件的方法有很多种,今天我要和大家分享的这种方法是针对特定的文件类型来用python方法完成备份。简单的来理解就是:我们只对某个特定后缀名的文件进行检测及备份;在for file in files 循环的内部加一个适当的测试就可以实行了。

Python 文件备份

这里举一个例子:
name, ext = os.path.splitext(file) if ext not in ('.py', '.txt', '.doc'):continue
代码片段首先使用了python标准库模块中os.path的splitext函数,用来获得文件的扩展名(以一个句号开始),放入局部变量ext中;
当检测到这个扩展名并不是我们的目标,那就执行continue语句来开始下一轮循环中。

Python特定文件备份方法源码示例如下:

import sys, os, shutil, filecmpMaxVersions = 100def backup(tree_top, bakdir_name = 'bakdir'):    for dir, subdirs, files in os.walk(tree_top):        #make sure each dir has subdir called bakdir        backup_dir = os.path.join(dir, bakdir_name)        if not os.path.exists(backup_dir):            os.makedirs(backup_dir)        #stop recurse the backup dir        subdirs[:] = [ d for d in subdirs if d != bakdir_name ]        for file in files:            filepath = os.path.join(dir,file)            destpath = os.path.join(backup_dir, file)        #check if the old version exist            for index in xrange(MaxVersions):                backup = '%s.%2.2d' % (destpath, index)                if not os.path.exists(backup):                    break            if index > 0:            #there is no need to backup if the file is the same as the new version                old_backup = '%s.%2.2d' %(destpath, index-1)                abspath = os.path.abspath(filepath)                try:                    if os.path.isfile(old_backup) and filecmp.cmp(abspath, old_backup,shallow = False):                        continue                except OSError:                    pass            try:                shutil.copy(filepath, backup)            except OSError:                passif __name__ == '__main__':    #backup dir    try:        tree_top = sys.argv[1]    except IndexError:        tree_top = '.'    backup(tree_top)

编橙之家文章,

评论关闭