Vahid Kharazi
Vahid Kharazi

Reputation: 6033

How can unrar a file with python

How can I extract a .zip or .rar file using Python?

Upvotes: 50

Views: 147603

Answers (5)

Romibuzi
Romibuzi

Reputation: 194

A good package for it is rarfile :

Here is an example:

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

Infos and docs here :

https://pypi.python.org/pypi/rarfile/

https://rarfile.readthedocs.io/api.html

Upvotes: 13

Alexander
Alexander

Reputation: 17291

This method only requires having 7zip installed.
Works flawlessly on every system 7zip does.
No python packages needed at all.

import subprocess
subprocess.run('7z x -oOutdir archive.rar')

The subprocess module is comes with python.

Upvotes: 4

Shital Shah
Shital Shah

Reputation: 68738

After some deep diving, here are my findings:

  • RAR is not an free open format and is owned by RARLabs. You must install their DLL or exe first to work with RAR. Some programs like 7zip might already include this with them.
  • patool is application that provides uniform command line as wrapper to other external compression applications. Natively, it can only deal with TAR, ZIP, BZIP2 and GZIP without needing external support.
  • pyunpack is Python library that can only deal with zip natively but provides interface to patool.

With this in mind, following things worked for me:

  • Make sure 7zip is installed
  • pip install patool pyunpack

Then to use it,

import pyunpack

pyunpack.Archive(archive_file).extractall(extract_dir)

Upvotes: 14

Amir
Amir

Reputation: 2258

Late, but I wasn't satisfied with any of the answers.

pip install patool
import patoolib
patoolib.extract_archive("foo_bar.rar", outdir="path here")

Works on Windows and linux without any other libraries needed.

Upvotes: 53

Irakli Darbuashvili
Irakli Darbuashvili

Reputation: 331

Try the pyunpack package:

from pyunpack import Archive
Archive('a.zip').extractall('/path/to')

Upvotes: 24

Related Questions