如何 tar 目录中的所有文件而不是目录本身

How to tar all the files in the directory but not the directory itself

我要tar指定目录下的所有文件。但我不想获取目录 tar'ed 也不是子目录。目前我有这个

>>> import tarfile
>>> with tarfile.open("x.gz","w:gz") as tar:
...     tar.add("a", arcname=os.path.basename("a")) #a is the directory

但它也是 tar 目录和子目录。

我认为您必须遍历目录的内容并将每个文件一一添加到其中:

for elem in os.scandir('a'):
    if elem.is_file:
        tar.add(elem.path)