简体   繁体   中英

Extract single file from RAR archive with rarfile in Python

I have a RAR archive with 2 files and I want to extract only one. I found in another answer that I could use the rarfile package, which according to the documentation contains the extract function. However, when I try to run a script I get a FileNotFoundError: [WinError 2] and the following information: During handling of the above exception, another exception occurred : ... rarfile.RarCannotExec: Unrar not installed? (rarfile.UNRAR_TOOL='unrar') rarfile.RarCannotExec: Unrar not installed? (rarfile.UNRAR_TOOL='unrar') .

From the information I could find, I saw it could be related with the absence of the Unrar.exe executable in the PATH and I tried to add it, but nothing changed. Another suggestion was to add rarfile.UNRAR_TOOL='unrar' to the script as a way to configure the behavior of the package, again same error.

This is my MWE, written and tested in Python 3.5.3:

from rarfile import RarFile

with RarFile('Test.rar') as file:
    file.extract(file.namelist()[0])

The file is being properly opened, since file.namelist() returns the archive's contents.

Thanks in advance!

Update based on OP comments :

I managed to unpack just one file using the following code

from rarfile import RarFile
RarFile.UNRAR_TOOL='C:\\full\\path\\to\\UnRARDLL.exe'

with RarFile('test.rar') as file:
    file.extract(file.namelist()[0])

Download UnRARDLL.exe and provide the correct full path to RarFile.UNRAR_TOOL .


You may want to use patool

import patoolib
patoolib.extract_archive("Test.rar", outdir="/some/dir")

Works on windows and linux , no extra software needed.
To install use: pip install patool

If the RAR file uses compression, you must use unrar (or something based on the unrar source code) in some way. If no compression is used, rarfile can do it all for you.

The solution from Pedro Lobito must work. If you get FileNotFoundError , I suggest you recheck your file names and paths again. In your question you say: rarfile.UNRAR_TOOL='unrar' , but the capitalization of rarfile must be RarFile as shown above by Pedro. Both are proper code but they have a different meaning. Also try by using the full path and don't forget the .exe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM