Search code examples
pythonextractrar

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').

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!


Solution

  • 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