How to unpack .rar file in Python?

9.9k views Asked by At

I have a problem in unpacking .rar files in Python. I am using macOS, with Anaconda Navigator and Spyder IDE. I have already installed unrar, pyunpack, py7zr, rarfile, patool packages. However, when I run this code:

import zipfile

import numpy as np
import pandas as pd
from rarfile import RarFile
import patoolib
from pyunpack import Archive

# Archive('aaa.rar').extractall(".")
patoolib.extract_archive('aaa.rar')

I get the error message:

PatoolError: could not find an executable program to extract format rar; candidates are (rar,unrar,7z),

and

File "/opt/anaconda3/lib/python3.7/site-packages/patoolib/__init__.py", line 684, in extract_archive
    return _extract_archive(archive, verbosity=verbosity, interactive=interactive, outdir=outdir, program=program)

  File "/opt/anaconda3/lib/python3.7/site-packages/patoolib/__init__.py", line 470, in _extract_archive
    program = find_archive_program(format, 'extract', program=program)

  File "/opt/anaconda3/lib/python3.7/site-packages/patoolib/__init__.py", line 336, in find_archive_program
    raise util.PatoolError("could not find an executable program to %s format %s; candidates are (%s)," % (command, format, ",".join(programs)))

Can somebody help me, please?

2

There are 2 answers

1
ItamarG On

You can use rarfile module

import rarfile

rf = rarfile.RarFile("myarchive.rar")
for f in rf.infolist():
    print(f.filename, f.file_size)
    if f.filename == "README":
        print(rf.read(f))
1
rlchqrd On

The issue is that unrar (and other programs you've installed locally) are not findable by Anaconda from within an Anaconda environment. The solution is to install them within that environemtn.


From within your Anaconda environment,

conda install unrar

will make unrar available, and make Python packages like patoolib that depend on it work.


Conda also provides a conda package for handling .rar files, which can be installed with

conda install -c conda-forge 7zip

More information on Conda environments can be found here. In particular they say one of the benefits of a Conda environment is that it "Manages non-Python dependencies (R, Perl, arbitrary executables).", of which unrar is an arbitrary executable.