首先需要安裝winrar,然後複製安裝目錄到path或者複製WinRAR.exe到C:\Windows
在cmd中輸入:rar 驗證
代碼:
import os
import time
source= r'C:\\temp'
target_dir = 'C:\\python'
target=target_dir + os.sep + time.strftime('%Y%m%d%H%M%S')+'.rar'
#target=target_dir + os.sep + time.strftime('%Y%m%d%H%M%S')+'.zip'#zip_command = "zip -qr {0} {1}".format(target,' '.join(source))
rar_command = "WinRAR A {0} {1}".format(target,''.join(source))print(rar_command)
if os.system(rar_command) == 0:
print('Successful backup to',target)
else:
print('Backup FAILED')
需要注意的是windows和linux中的壓縮命令不一致
參考:A Byte of Python3(中文版).pdf