Python's tar.gz format compression and decompression

  • Python's tar.gz format compression and decompression

The difference between tar and tar.gz tools

The tar file just packs the file, and the file size does not change; tar.gz compresses the file.

Brief description:

Usually python is used to package files or folders into tar.gz files using relative paths, and by default. After using tarfile to package into tar.gz, it will have an absolute path by default. In many cases, what is needed is a compressed package with a relative path.

Implementation code:

For example, package the folder of E:\Work\python\01\test.

import os, tarfile

tmp_tar_dir = r'E:\Work\python\01\test'
tmp_filename = "test.tar.gz"
tmp_dir = r'E:\Work\python\01'

#一次性打包整个根目录。空子目录会被打包。
#如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。
def make_targz(output_filename, source_dir):
  with tarfile.open(output_filename, "w:gz") as tar:
    tar.add(source_dir, arcname=os.path.relpath(tmp_dir))

#逐个添加文件打包,未打包空子目录。可过滤文件。
#如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。
def make_targz_one_by_one(output_filename, source_dir):
  tar = tarfile.open(output_filename,"w:gz")
  for root,dir,files in os.walk(source_dir):
    root_ = os.path.relpath(root,start=source_dir)
    for file in files:
      pathfile = os.path.join(root, file)
      tar.add(pathfile, arcname=os.path.join(root_,file))
  tar.close()

# 解压缩
def untar(fname, dirs):
    t = tarfile.open(fname)
    t.extractall(path = dirs) 

if __name__ == "__main__":

    make_targz("test.tar.gz", tmp_tar_dir)
    make_targz_one_by_one("test1.tar.gz",tmp_tar_dir)
    untar(r'E:\Work\python\01\test.tar.gz', r'E:\Work\python\01\os')      

run and test

 python -u "e:\Work\python\01\tar.py"

insert image description here

おすすめ

転載: blog.csdn.net/Youning_Yim/article/details/127747592