tar_fileobj = io.BytesIO() with tarfile.open(fileobj=tar_fileobj, mode="w|") as tar: my_content = "abdef".encode('utf-8') tf = tarfile.TarInfo("my_file_name") tf.size = len(my_content) tar.addfile(tf, io.BytesIO(my_content)) tar_fileobj.seek(0)