您的位置:首页 > 其它

目录文件备份工具

2007-10-17 23:03 183 查看

# -*- 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()

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: