Python特定文件备份方法源码示例,,Python备份文件的方
Python特定文件备份方法源码示例,,Python备份文件的方
Python备份文件的方法有很多种,今天我要和大家分享的这种方法是针对特定的文件类型来用python方法完成备份。简单的来理解就是:我们只对某个特定后缀名的文件进行检测及备份;在for file in files 循环的内部加一个适当的测试就可以实行了。
这里举一个例子:
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)
编橙之家文章,
相关内容
- python科学计算贝塞尔函数最大最小值,python贝塞尔,这是
- python lambda实现求素数的简短代码,pythonlambda素数,用P
- Python多进程读取文件操作方法详解,,python读取文件的操
- 用Python代码实现阿拉伯数字与罗马数字转换讲解,pyt
- Linux环境下的Python翻译工具源码,linuxpython,编橙之家P
- Python实时监控Linux cpu使用率实现方法,pythonlinux,Python监
- 用python遍历方法统计linux内核文件的行数示例,,用pyt
- python statvfs方法获知磁盘的空间量,pythonstatvfs,python s
- python监控用户登陆并发送通知邮件方法,python用户登陆
- Python迅雷快车旋风地址加密解密,python加密解密,Pytho
评论关闭