目录文件备份工具

备份目录工具
# -*- coding: cp936 -*-
'''这个程序实现了备份目录的功能,
演示了如下
1)shutil模块中copy/copytree的使用方法;
2)os.path模块isfile/isdir/join的使用方法
3)递归方法使用
'''
import shutil
import os
def backupDir(pathsrc,pathdest):
    
'''备份目录pathsrc到pathdest
    实现方法:
    查找源目录中的所有目录和文件,对每一项进行比较:
    1)如果源目录中的item不存在,直接复制到目标目录即可
    2)如果源目录中的item是目录,则进行递归调用
    3)如果源目录中的item是文件,比较的修改日期,如果源文件比目标文件新,则复制文件,否则不予处理
    4) 不是目录或文件,直接复制,不再进行其他的判断
    
'''
    
if os.path.isdir(pathsrc):
        os.chdir(pathsrc)
        
for item in os.listdir(pathsrc):
            itemsrc 
= os.path.join(pathsrc,item)
            itemdest 
= os.path.join(pathdest,item)
            
# 先判断文件或目录是否存在,如果目标目录中没有这个文件或目录,直接复制即可
            if os.path.exists(itemdest):
                
# 如果是目录,进行递归调用
                if os.path.isdir(itemsrc):
                    backupDir(itemsrc,itemdest)
                
# 如果是文件,进行修改时间的比较,若修改时间变化,覆盖目标文件
                elif os.path.isfile(itemsrc):
                    
if os.path.exists(itemdest):
                        
if os.stat(itemsrc)[-2> os.stat(itemdest)[-2]:
                            shutil.copy(itemsrc,itemdest)
                
else:
                    
# 其他情况直接复制,不论是否改变
                    shutil.copy(itemsrc,itemdest)
            
else:
                
# 如果不存在,复制整个目录或文件
                if os.path.isdir(itemsrc):
                    shutil.copytree(itemsrc,itemdest)
                
elif os.path.isfile(itemsrc):
                    shutil.copy(itemsrc,itemdest)
        os.chdir(
'..')
        
return
    
else:
        
return

# backupDir('c:/1','c:/2')

from Tkinter import *
root 
= Tk()
# 创建源目录
Label(root,text = "source directory:").grid(row = 0,column = 0,stick = W)
vSource 
= StringVar()
vSource.set(
'c:/1')
Entry(root,textvariable 
= vSource).grid(row = 0,column = 1)
# 创建目标目录
Label(root,text = "destination directory:").grid(row = 1,column = 0,stick = W)
vDestination 
= StringVar()
vDestination.set(
'c:/2')
Entry(root,textvariable 
= vDestination).grid(row = 1,column = 1)

# 创建备份按钮
Button(root,text = 'start backup directory',
       command 
= lambda arg1 = vSource.get(),arg2 = vDestination.get():backupDir(arg1,arg2)
       ).grid(row 
= 2,column = 0,columnspan = 2,stick = E + W + N + S)
root.mainloop()
 
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值