Continuing with the example provided in the related question, you can do this as follows:
import tarfile import StringIO import time tar = tarfile.TarFile("test.tar", "w") string = StringIO.StringIO() string.write("hello") string.seek(0) info = tarfile.TarInfo(name='dir') info.type = tarfile.DIRTYPE info.mode = 0755 info.mtime = time.time() tar.addfile(tarinfo=info) info = tarfile.TarInfo(name='dir/foo') info.size=len(string.buf) info.mtime = time.time() tar.addfile(tarinfo=info, fileobj=string) tar.close()
Be careful with the mode attribute, because the default value may not include execute permissions for the directory owner, which is necessary to change it and get its contents.
source share