Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python tarfile recursive extract in memory

Tags:

python

I have a tar file with that contains compressed tar files. Like this:

gnomeAware@devserv:~$ tar tf test.tar
File1.tar.gz
File2.tar.gz
File3.tar.gz
File4.tar.gz

tarfile expects a string as the file to open. Is there anyway to pass it a file object?

tar = tarfile.open('test.tar', 'r') # Unpack tar
for item in tar:
  Bundle=tar.extractfile(item) # Pull out the file
  t = tarfile.open(Bundle, "r:gz") # Unpack tar
  for tItem in t:
  ...

Thanks.

like image 973
gnomeAware Avatar asked Jan 07 '23 03:01

gnomeAware


1 Answers

the definition of tarfile.open looks like this def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):

And python documentation says that

If fileobj is specified, it is used as an alternative to a file object opened for name. It is supposed to be at position 0.

so, instead of calling it with positional argument, you can call it with a keyword argument. Pass a fileobj instead of the name.

import tarfile

f = open('archive.tar', 'rb')
print (f)
tar = tarfile.open(fileobj=f, mode='r:') # Unpack tar
for item in tar:
    print(item)
like image 82
Ward Avatar answered Jan 17 '23 21:01

Ward