How can files be added to a tarfile with Python, without adding the directory hierarchy?

前端 未结 4 1994
甜味超标
甜味超标 2020-12-13 05:30

When I invoke add() on a tarfile object with a file path, the file is added to the tarball with directory hierarchy associated. In other words, if

4条回答
  •  不思量自难忘°
    2020-12-13 06:14

    thanks to @diabloneo, function to create selective tarball of a dir

    def compress(output_file="archive.tar.gz", output_dir='', root_dir='.', items=[]):
        """compress dirs.
    
        KWArgs
        ------
        output_file : str, default ="archive.tar.gz"
        output_dir : str, default = ''
            absolute path to output
        root_dir='.',
            absolute path to input root dir
        items : list
            list of dirs/items relative to root dir
    
        """
        os.chdir(root_dir)
        with tarfile.open(os.path.join(output_dir, output_file), "w:gz") as tar:
            for item in items:
                tar.add(item, arcname=item)    
    
    
    >>>root_dir = "/abs/pth/to/dir/"
    >>>compress(output_file="archive.tar.gz", output_dir=root_dir, 
                root_dir=root_dir, items=["logs", "output"])
    

提交回复
热议问题