python利用unrar實現rar文件解壓縮


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()

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM