python Unzips an instance of an TAR file to a specified folder

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

As follows:


######### Extract all files from src_dir to des_dir
def extract_tar_files(src_dir,des_dir):
  files = os.listdir(src_dir)
  for file in files:
    dir_tmp = os.path.join(src_dir, file)
    print dir_tmp
    if not os.path.isdir(dir_tmp): ## Is a file, not a folder 
      # Unzip a specific file 
      if dir_tmp.endswith("gz") and (dir_tmp.find(cs.Port_week_perfer_name_start) != -1):
        #f = zipfile.ZipFile(dir_tmp, mode="r")
        f = tarfile.open(dir_tmp)
        names = f.getnames()
        for name in names:
          f.extract(name, path=des_dir)
    else:
      extract_tar_files(dir_tmp,des_dir)
  return 0

Related articles: