Skip to content

Instantly share code, notes, and snippets.

@khaotik
Created May 2, 2021 11:53
Show Gist options
  • Save khaotik/31d17ee5c2ea4372a3c125ea762f6dac to your computer and use it in GitHub Desktop.
Save khaotik/31d17ee5c2ea4372a3c125ea762f6dac to your computer and use it in GitHub Desktop.
Minimal python tarfile module usage
#!/usr/bin/env python
import io
import tarfile
a_content = '''
content:aaa
content:111
'''
b_content = '''
content:bbb
content:222
'''
def addBytesToTar(tar_, arcname:str, buf:bytes):
tar_info = tarfile.TarInfo(arcname)
tar_info.size = len(buf)
return tar_.addfile(tar_info, io.BytesIO(buf))
def addTextFileToTar(tar_, arcname:str, s_:str):
buf = s_.encode()
return addBytesToTar(tar_, arcname, buf)
TarInfo = tarfile.TarInfo
with tarfile.open('a.tar', 'w|') as tar:
addTextFileToTar(tar, 'a.txt', a_content)
addTextFileToTar(tar, 'b.txt', b_content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment