花了大半天的时间,结合文档中的例子,自己写了一个Windows下使用WinRAR压缩的功能。代码如下:
# coding=utf-8
# 备份文件与压缩:gzip、zipfile、rar
import os,glob
import time
import zipfile
import gzip
# 三、使用rar压缩文件
# 用WinRAR的rar命令压缩文件,首先要安装有WinRAR且设置WinRAR到环境变量的路径Path中。
# 验证环境是否正常,可在cmd模式下输入:rar a D:/Python27/test D:/Python27/test,能够正常执行就OK。
# 我第一次验证时cmd可以执行成功,但是跑下面的代码不成功。最后重启了电脑,再执行就成功了。
source = r'D:\Python27\test'
target_dir = 'D:\\Python27\\'
# The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the rar archive
now = time.strftime('%H%M%S')
print now
# Take a comment from the user to create the name of the rar file
comment = raw_input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.rar' # The name of the rar file
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.rar'
# Notice the backslash!
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
# Use the rar command to put the files in a rar archive
rar_command = "rar a %s %s" %(target,''.join(source)) # join方法把source列表转换为字符串
print rar_command
# Run the backup
if os.system(rar_command) == 0:
print 'Successful backup', target
else:
print 'Failed!'
执行结果:
>>> ================================ RESTART ================================>>>
content: Lots of content here
Lots of content here
Successful backup to test2.zip
data.py (2014, 7, 25, 14, 27, 10) 3384 1620
file.py (2014, 7, 22, 17, 57, 52) 1482 640
NEWS.txt (2013, 5, 15, 22, 41, 12) 359882 130523
160803
Enter a comment --> added new comment
rar a D:\Python27\20140730\160803_added_new_comment.rar D:\Python27\test
Successful backup D:\Python27\20140730\160803_added_new_comment.rar
>>>