Python Backup files

Source: Internet
Author: User
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]
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.