Created
July 13, 2015 18:11
-
-
Save rzilleruelo/be782b662de59684d561 to your computer and use it in GitHub Desktop.
Encode multiples python objects into a tar file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from io import BytesIO | |
import pickle | |
import tarfile | |
def _is_tar(tar_candidate): | |
return type(tar_candidate) == tarfile.TarFile | |
def _write_tar(tar, name, get_data): | |
data = get_data() | |
info = tarfile.TarInfo(name=name) | |
info.size=len(data) | |
tar.addfile(tarinfo=info, fileobj=BytesIO(data)) | |
def _with_tar(stream, action, mode='w'): | |
if _is_tar(stream): | |
tar = stream | |
else: | |
tar = tarfile.TarFile(stream, mode=mode) | |
action_response = action(tar) | |
if not _is_tar(stream): | |
tar.close() | |
return action_response | |
def _read_tar(input_, name): | |
if _is_tar(input_): | |
tar = input_ | |
else: | |
tar = tarfile.open(input_, mode='r') | |
data = pickle.load(tar.extractfile(name)) | |
if not _is_tar(input_): | |
tar.close() | |
return data | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment