代码如下:
#-*- coding: utf-8 -*-
import os
import time
#step1:需要备份的文件
source='F:\\backuptest\\source\\aa.txt'
#step2:存储备份文件的位置
target_dir='F:\\backuptest\\'
#step3:将备份文件压缩成rar
#step4:当前日期作为目录名
today=target_dir+time.strftime('%Y%m%d')
#step4:当前时间
now=time.strftime('%H%M%S')
#step4:用户注释
comment=raw_input('Enter a comment-->')
if len(comment)==0:
target=today+os.sep+now+'.rar'
else:
target=today+os.sep+now+'_'+\
comment.replace('','_')+'.rar'
#是否需要创建目录
if not os.path.exists(today):
os.mkdir(today)
print "Successfully created directory",today
#step5:使用备份命令
rar_command='"C:\\Program Files\\WinRAR\\WinRAR.exe" A %s %s -r' % (target,source)
# rar_command='"C:\\Program Files\\WinRAR\\WinRAR.exe" A %s %s -r' % (target,source)
if os.system(rar_command)==0:
print "Successfully backup to",target
else:
print "Backup FAILED"
说明:
1)个人觉得自然字符串容易出问题,所以都使用转义字符
2)备份命令里必须是WinRAR的安装路径,否则命令无法执行
3)备份命令中的‘A’不可缺少,否则虽然显示备份成功 但会找不到备份的文件
本文介绍了如何在Python环境下,利用WinRAR在Windows操作系统中执行备份操作。重点强调了在构建备份命令时需要注意使用转义字符,确保WinRAR的完整路径,并且指出'А'参数对于成功创建备份文件的重要性。
194

被折叠的 条评论
为什么被折叠?



