python implements packaging a file or folder as an tar.gz file in a relative path

  • 2021-06-28 09:26:38
  • OfStack

By default, the tar.gz file packaged by tarfile takes an absolute path, whereas in many cases, we need a path relative to the packaged folder.

Code:


<pre name="code" class="python"><span style="font-size:18px;">import tarfile
tmp_tar_dir = "/home"
file_name = "test.tar.gz"
tmp_dir = "/home/centos"
soft_name = "php"
tar = tarfile.open(os.path.join(tmp_tar_dir,file_name),"w:gz")
for root,dir,files in os.walk(os.path.join(tmp_dir,soft_name)):
 root_ = os.path.relpath(root,start=tmp_dir)
 #tar.add(root,arcname=root_)
 for file in files:
  full_path = os.path.join(root,file)
  tar.add(full_path,arcname=os.path.join(root_,file))
tar.close()</span>

Note: If there is always an empty folder in the original directory, the packaged file does not contain the empty folder.


Related articles: