国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python實(shí)現(xiàn)定期檢查源目錄與備份目錄的差異并進(jìn)行備份功能示例

2020-02-16 01:23:47
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了Python實(shí)現(xiàn)定期檢查源目錄與備份目錄的差異并進(jìn)行備份功能。分享給大家供大家參考,具體如下:

在項(xiàng)目中,經(jīng)常要更新文件,在更新之前首先要備份源文件,所以就用到了這個(gè)腳本(來(lái)自于Python自動(dòng)化運(yùn)維這本書),總共有以下幾個(gè)步驟:

1. 獲取要進(jìn)行比較的兩個(gè)目錄,進(jìn)行差異比較,把源目錄特有的文件或目錄、以及和備份目錄不同的文件或目錄保存到列表中,并且判斷目錄下面是否還有目錄,遞歸進(jìn)行保存這些差異文件。
2. 將差異文件列表中文件或目錄的路徑換成對(duì)應(yīng)的備份路徑,進(jìn)行判斷,如果備份路徑不存在,就創(chuàng)建目錄。
3. 繼續(xù)對(duì)比源目錄和新創(chuàng)建的備份目錄中的差異文件,把源路徑換成備份目錄的路徑。
4. 然后遍歷復(fù)制源目錄文件到備份目錄。

以下是具體的實(shí)現(xiàn)代碼:

#!/usr/bin/env python# -*- coding: utf-8 -*-import os, sysimport filecmpimport reimport shutilholderlist = []##對(duì)應(yīng)第一個(gè)步驟def compare_me(dir1, dir2):  dircomp = filecmp.dircmp(dir1, dir2)  only_in_one = dircomp.left_only  diff_in_one = dircomp.diff_files  dirpath = os.path.abspath(dir1)  [ holderlist.append(os.path.abspath(os.path.join(dir1, x))) for x in only_in_one ]  [ holderlist.append(os.path.abspath(os.path.join(dir1, x))) for x in diff_in_one ]  if len(dircomp.common_dirs) > 0:    for item in dircomp.common_dirs:      compare_me(os.path.abspath(os.path.join(dir1, item)), os.path.abspath(os.path.join(dir2, item)))  return holderlist##對(duì)應(yīng)第二個(gè)步驟def main():  if len(sys.argv) > 2:    dir1 = sys.argv[1]    dir2 = sys.argv[2]  else:    print "Usage: ", sys.argv[0], "datadir backupdir"    sys.exit()  source_files = compare_me(dir1, dir2)  dir1 = os.path.abspath(dir1)  if not dir2.endswith('/'):    dir2 = dir2 + '/'  dir2 = os.path.abspath(dir2)  destination_files = []  createdir_bool = False  for item in source_files:    destination_dir = re.sub(dir1, dir2, item)    destination_files.append(destination_dir)    if os.path.isdir(item):      if not os.path.exists(destination_dir):        os.makedirs(destination_dir)        createdir_bool = True   ##對(duì)應(yīng)第三個(gè)步驟  if createdir_bool:    destination_files = []    source_files = []    source_files = compare_me(dir1, dir2)    for item in source_files:      destination_dir = re.sub(dir1, dir2, item)      destination_files.append(destination_dir)  ##對(duì)應(yīng)第四個(gè)步驟  print "update item: "  print source_files  copy_pair = zip(source_files, destination_files)  print "copy_pair is %s" % copy_pair  for item in copy_pair:    print "item is %s, %s" % (item[0], item[1])    if os.path.isfile(item[0]):      shutil.copyfile(item[0], item[1])if __name__ == '__main__':  main()

最后根據(jù)需要,可以設(shè)定一個(gè)定時(shí)檢查,進(jìn)行自動(dòng)同步源目錄和備份目錄,讓其保持一致性。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宁都县| 白水县| 腾冲县| 岢岚县| 禹城市| 孙吴县| 贵定县| 甘南县| 通榆县| 内乡县| 任丘市| 信宜市| 南陵县| 当阳市| 盐城市| 博爱县| 永宁县| 临海市| 青神县| 西乌珠穆沁旗| 思茅市| 扎鲁特旗| 江孜县| 河北区| 营口市| 南阳市| 雷州市| 南川市| 浠水县| 丰城市| 河曲县| 东乡族自治县| 莱芜市| 宁国市| 搜索| 紫金县| 出国| 攀枝花市| 灵寿县| 华亭县| 且末县|