用python在windows下备份

来源:互联网 发布:农村淘宝下载安装 编辑:程序博客网 时间:2024/05/16 16:56
我想把桌面上的lala.taxt文件压缩备份到d盘:
lala.txt在c:\users\wangxiaozhen\desktop\lala.txt下
然后备份就好了(我用的是winrar压缩的,它兼容zip,压缩效率较高)
需要注意的是要把F:\Program Files\WinRAR路径添加到系统环境中,否则会出现'rar' 不是内部或外部命令,也不是可运行的程序
或批处理文件。这种错误。
添加路径可以自己百度
# -*- coding: cp936 -*-import osimport time# 在列表中写明需要备份的文件名和或目录source=[r'"c:\users\wangxiaozhen\desktop\lala.txt"']# 备份到下面的目录中target_dir='d:\\'# 备份为rar文件,文件名是: 年月日时分秒.rartarget = target_dir + "lalala" + '.rar'# 用winrar的命令行来压缩文件,前提是winrar在windowsXP的path中zip_command="rar a %s %s"%(target, ' '.join(source) ) #运行这个备份程序来备份if os.system(zip_command) == 0:print 'Successful backup to', targetelse:print 'Backup FAILED!'
输入多个文件或文件夹,使之压缩备份
#!/usr/bin/python# -*- coding: cp936 -*-import osimport timesource = [] #许多待备份文件用列表存起来running = 1while 1:    your_source = raw_input("Your own path or your own file path:")    #如果使用input(),在运行后输入路径名时,需要在两边加上" ",下面的input同理    #比如欲备份E盘下zipme文件夹里的hello.txt文件,则应输入zipme\\hello.txt    source.append(your_source)    if int(raw_input("Do you want to ji xun add file or folder(1/0):"))==0:        break#print sourcetarget_dir = 'E:\\h\\' #备份生成的文件存放的路径(压缩后的文件放在e盘下的h文件夹中)#以当前日期和时间为文件名命名生成的压缩文件target = target_dir+time.strftime('%Y%m%d%H%M%S')+'.rar'#使用zip命令压缩文件zip_command="rar a %s %s"%(target, ' '.join(source) )#通过给系统传递参数来执行压缩命令(压缩使用的是WinRAR所带文件rar.exe来执行压缩)if os.system(zip_command) == 0:    print('Successful backup to',target)else:    print('Backup FAILED')