1. 使用`os.system`调用系统命令:
import os
import time
source = ['D:\\Work\\Python\\Demo', 'd:\\work\\linux']
target_dir = 'D:\\Work\\backup\\'
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.rar'
zip_command = 'rar a %s %s' % (target, ' '.join(source))
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup Failed')
2. 使用`rarfile`库(需要安装`rarfile`库):
import rarfile
def set_path(path: str):
os_path = os.environ.get('path')
if path in os_path:
return
if os.path.exists(path):
os.environ['path'] = f'{os_path};{path}'
else:
raise ValueError('Environment variable path does not exist')
def extract_rar(rar_path: str, output_dir: str):
with rarfile.RarFile(rar_path, 'r') as rf:
rf.extractall(output_dir)
示例使用
set_path('C:\\Program Files\\WinRAR\\WinRAR.exe') 设置WinRAR路径
extract_rar('path_to_your_rar_file.rar', 'path_to_output_directory')
3. 使用`unrar`库(需要安装`unrar`库):
import unrar
def extract_rar(rar_path: str, output_dir: str):
with unrar.RarFile(rar_path, 'r') as rf:
rf.extractall(output_dir)
示例使用
extract_rar('path_to_your_rar_file.rar', 'path_to_output_directory')
请确保在尝试以上代码之前已经安装了相应的库,并且根据你的操作系统调整路径和环境变量设置。如果你使用的是Linux系统,你可能需要使用`unrar`命令而不是`rar`命令。