python利用unrar实现rar文件解压缩

时间:2021-06-19 09:15:44

python第三方包unrar可以实现rar文件的解压缩,它以动态库UnRAR为基础,封装而成

1. 下载UnRAR动态库

  https://pypi.python.org/pypi/unrar/0.2

  windows下可以下载编译好的库包:

  http://www.rarlab.com/rar/UnRARDLL.exe

  下载解压后能得到一个DLL: UnRAR.dll

2. 安装python包unrar

  pip install unrar

  windows下先进入python安装目录下的Scripts: 例如“D:\Python27\Scripts”

  然后同样执行: pip install unrar

3. 开始使用unrar

  我们在命令行中直接演示使用方法:

  将1中解压得到的UnRAR.dll放到当前目录下,否则会找不到DLL的路径

  在unrarlib.py("python安装目录\Python27\Lib\site-packages\unrar")中有实现:

if platform.system() == 'Windows':
from ctypes.wintypes import HANDLE as WIN_HANDLE
HANDLE = WIN_HANDLE
UNRARCALLBACK = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint,
ctypes.c_long, ctypes.c_long,
ctypes.c_long)
lib_path = lib_path or find_library("unrar.dll")
if lib_path is None:
#lib_path = 'E:\\code\\python\\unrar\\Python27\\Lib\\site-packages\\unrar\\UnRAR.dll'
lib_path = 'UnRAR.dll'
if lib_path:
unrarlib = ctypes.WinDLL(lib_path)

 

>>> from unrar import rarfile
>>> rar = rarfile.RarFile('sample.rar')
>>> rar.namelist()
[u'test_file.txt']
>>> rar.printdir()
File Name Modified Size
test_file.txt 2013-04-14 08:20:28 17
>>> rar.testrar()
>>> info = rar.infolist()[0]
>>> info.filename
u'test_file.txt'
>>> info.file_size
17L
>>> info.date_time
(2013L, 4L, 14L, 8L, 20L, 28L)
>>> rar.extractall()