你想對某個目錄樹中的被修改過的文件多次備份,以防止某次修改意外地抹去了你的編輯結(jié)果。 周期性的執(zhí)行以下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)
如果想針對某個特定后綴名的文件進行備份,(或?qū)Τツ硞€擴展名之外的文件進行備份);在 for file in files 循環(huán)內(nèi)加一個適當?shù)臏y試即可:
for file in files: name,ext = os.path.splitext(file) if ext not in ('.py','.txt','.doc'): continue
注意以下代碼,避免os.walk遞歸到要備份的子目錄。當os.walk迭代開始之后,os.walk根據(jù)subdirs來進行子目錄迭代。這個關(guān)于os.walk的細節(jié)也是生成器應(yīng)用的一個絕佳例子,它演示了生成器是如何通過迭代的代碼獲取信息,同時又是如何反過來影響迭代。
subdirs[:] = [d for d in subdirs if d != bakdir_name]
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com