from io import BytesIO import os.path import tarfile from tempfile import TemporaryDirectory # Create a temporary directory with one empty file in it. with TemporaryDirectory() as directory: with open(os.path.join(directory, "empty.txt"), mode="w"): pass # Create two tarfiles, one matching the directory name, and one not. io_1 = BytesIO() with tarfile.open(mode="w", fileobj=io_1) as tar_1: tar_1.add(directory) print("First tar contents, with no name:") tar_1.list() print() io_2 = BytesIO() with tarfile.open(name=directory, mode="w", fileobj=io_2) as tar_2: tar_2.add(directory) print("Second tar contents, with name matching directory:") tar_2.list()