问题
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')
.
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!
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/43527641/extract-single-file-from-rar-archive-with-rarfile-in-python