python备份文件

任务:

你想对某个目录树中的被修改过的文件多次备份,以防止某次修改意外地抹去了你的编辑结果。 周期性的执行以下python脚本可以对指定目录下的文件进行备份。

#-*- coding:utf-8 -*-
import sys,os,shutil,filecmp

MAXVERSIONS = 100

def backup(tree_top, bakdir_name="bakdir"):
	for dir,subdirs,files in os.walk(tree_top):
		#确保每个目录都有一个备份目录
		backup_dir = os.path.join(dir,bakdir_name)
		if not os.path.exists(backup_dir):
			os.makedirs(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)
			#检查以前的版本是否存在
			for index in xrange(MAXVERSIONS):
				backfile = '%s.%2.2d' % (destpath, index)
				if not os.path.exists(backfile):
					break
		if index > 0:
			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,backfile)
		except OSError:
			pass

if __name__ == '__main__':
	try:
		tree_top = sys.argv[1]
	except IndexError:
		tree_top = '.'
	backup(tree_top)

如果想针对某个特定后缀名的文件进行备份,(或对除去某个扩展名之外的文件进行备份);在 for file in files 循环内加一个适当的测试即可:

for file in files:
    name,ext = os.path.splitext(file)
    if ext not in ('.py','.txt','.doc'):
        continue

注意以下代码,避免os.walk递归到要备份的子目录。当os.walk迭代开始之后,os.walk根据subdirs来进行子目录迭代。这个关于os.walk的细节也是生成器应用的一个绝佳例子,它演示了生成器是如何通过迭代的代码获取信息,同时又是如何反过来影响迭代。

subdirs[:] = [d for d in subdirs if d != bakdir_name]

  

本段代码摘自《python cookbook》。

猜你喜欢

转载自null-386.iteye.com/blog/2064176