Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncompress an tar.bz2 file with Python tarfile module

Tags:

python

tarfile

I have many files with the extension "tar.bz2" and I want to uncompress them. So I use the "tarfile" module as explained here : https://docs.python.org/3/library/tarfile.html.

I try the following code :

import tarfile
tar = tarfile.open("path_to/test/sample.tar.bz2", "r:bz2")  
for i in tar:
  tar.extractall(i)
tar.close()

But nothing happens : the tar.bz2 file has not been uncompressed into the folder "path_to/test/".

Would you have any ideas ?
Thanks !

like image 469
Julien Avatar asked Dec 05 '22 03:12

Julien


2 Answers

You use tar.extractall with wrong argument. I think, you need something like this

import tarfile
tar = tarfile.open("path_to/test/sample.tar.bz2", "r:bz2")  
tar.extractall()
tar.close()

or

import tarfile
tar = tarfile.open("path_to/test/sample.tar.bz2", "r:bz2")  
for i in tar:
  tar.extractfile(i)
tar.close()

If you need to extract files to some specific folder

import tarfile
tar = tarfile.open("path_to/test/sample.tar.bz2", "r:bz2")  
tar.extractall(some_path)
tar.close()
like image 141
kvorobiev Avatar answered Dec 08 '22 05:12

kvorobiev


I like the context manager:

import tarfile

def extract_bz2(filename, path="."):
    with tarfile.open(filename, "r:bz2") as tar:
        tar.extractall(path)
like image 44
mja Avatar answered Dec 08 '22 04:12

mja