Search code examples
python-3.xtarfile

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


I want to tar all the files in the specified directory. But I don't want to get the directory tar'ed also not the sub-directories too. Currently I have this

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

But it is tar'ing the directory and sub-directories too.


Solution

  • I think you'll have to iterate over the contents of the directory and add each file in there one by one:

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