“Python云存储备份”的版本间的差异
来自CloudWiki
(→广度优先遍历目录) |
(→广度优先遍历目录) |
||
第33行: | 第33行: | ||
===广度优先遍历目录=== | ===广度优先遍历目录=== | ||
− | + | 选做的是代码 | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
==应用实战== | ==应用实战== |
2020年6月12日 (五) 02:06的版本
基础操作
比较左右两侧文件
import filecmp import os left = r"D:\teaching\人工智能" # 定义左目录 right = r"E:\20200311\teaching\人工智能" #定义右目录 #比较目录 dirobj = filecmp.dircmp(left, right, ['cmp.py']) #目录比较,忽略test.py文件 dirobj.report() print("left_only:") print(dirobj.left_only) # 只在左目录中的文件或目录
复制文件
import shutil for i in dirobj.left_only: left_file=os.path.realpath(i) right_file=os.path.join(right,i) print("左侧发现新文件/目录: "+i) print(left_file) print(right_file) s=input("是否复制?y/n") if s=='y': print("开始复制中...") shutil.copyfile(left_file,right_file) print("复制完毕"+right_file)
广度优先遍历目录
选做的是代码
应用实战
增量备份
本程序用于将文件增量备份到云端:
from os import listdir,makedirs from os.path import join, isfile, isdir import os import shutil,filecmp def usage(): print("目录路径不对 ~") def CopyToCloud(scrDir, dstDir): if ((not os.path.isdir(scrDir)) or (not os.path.isdir(dstDir)) or (os.path.abspath(scrDir)!=scrDir) or (os.path.abspath(dstDir)!=dstDir)): usage() return for item in os.listdir(scrDir): scrItem = os.path.join(scrDir, item) dstItem = scrItem.replace(scrDir,dstDir) if os.path.isdir(scrItem): #创建新增的文件夹,保证目标文件夹的结构与原始文件夹一致 if not os.path.exists(dstItem): os.makedirs(dstItem) print('make directory'+dstItem) #递归调用自身函数 CopyToCloud(scrItem, dstItem) elif os.path.isfile(scrItem): #只复制新增或修改过的文件 if ((not os.path.exists(dstItem)) or (not filecmp.cmp(scrItem, dstItem, shallow=False))): shutil.copyfile(scrItem, dstItem) print('file:'+scrItem+'==>'+dstItem) root_right=r'E:\20200311' root_left='D:\\' d=r"teaching\自动化运维" left=join(root_left,d) right=join(root_right,d) print(left,right) CopyToCloud(left,right)