Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct a TarFile object in memory from byte buffer in Python 3?

Is it possible to create a TarFile object in memory using a buffer containing the tar data without having to write the TarFile to disk and open it up again? We get the bytes sent over a socket.

Something like this:

import tarfile byte_array = client.read_bytes() tar = tarfile.open(byte_array) # how to do this? # use "tar" as a regular TarFile object for member in tar.getmembers():     f = tar.extractfile(member)     print(f) 

Note: one of the reasons for doing this is that we eventually want to be able to do this with multiple threads simultaneously, so using a temp file might be overridden if two threads try to do it at the same time.

Thank you for any and all help!

like image 258
Sefu Avatar asked Apr 07 '13 01:04

Sefu


People also ask

How do you make a tarball in Python?

Use the tarfile module to create a zip archive of a directory. Walk the directory tree using os. walk and add all the files in it recursively.

How do I open a Tarfile file in Python?

You can use the tarfile module to read and write tar files. To extract a tar file, you need to first open the file and then use the extract method of the tarfile module.


1 Answers

BytesIO() from IO module does exactly what you need.

import tarfile, io byte_array = client.read_bytes() file_like_object = io.BytesIO(byte_array) tar = tarfile.open(fileobj=file_like_object) # use "tar" as a regular TarFile object for member in tar.getmembers():     f = tar.extractfile(member)     print(f) 
like image 148
decaf Avatar answered Sep 21 '22 00:09

decaf