Task:
You want to back up the modified files in a directory tree multiple times to prevent a modification from accidentally erasing your edits. Periodically execute the following Python script to back up files in the specified directory.
#-*-coding:utf-8-*-import sys,os,shutil,filecmpmaxversions = 100def 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) # Check that the previous version exists for the for index in Xrange (maxversions): Backfile = '%s.%2.2d '% (destpath, index) if not os.path.exists (backfile): Breakif 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): continueexcept oserror:passtry: Shutil.copy (filepath,backfile) except oserror:passif __name__ = = ' __main__ ': try:tree_top = sys.argv[1]except Indexerror:tree_top = '. ' Backup (tree_top)
If you want to make a backup of a file for a specific suffix name (or a file that is removed from an extension), add an appropriate test to the for file in the files loop:
For file in Files: name,ext = os.path.splitext (file) if ext not in ('. Py ', '. txt ', '. Doc '): continue
Note the following code to avoid os.walk recursion to a subdirectory to be backed up. When the Os.walk iteration begins, Os.walk iterates through the subdirectories according to the Subdirs. This detail about Os.walk is also a great example of a generator application that demonstrates how the generator obtains information through iterative code, and how it affects iterations in turn.
subdirs[:] = [D for D in Subdirs if d! = Bakdir_name]