Python package folder method summary of zip tar tar. gz etc

  • 2020-05-12 02:48:59
  • OfStack

This article illustrates how Python packages folders. I will share it with you for your reference as follows:

1. zip


import os, zipfile
# Package directory is zip File (uncompressed) 
def make_zip(source_dir, output_filename):
  zipf = zipfile.ZipFile(output_filename, 'w')
  pre_len = len(os.path.dirname(source_dir))
  for parent, dirnames, filenames in os.walk(source_dir):
    for filename in filenames:
      pathfile = os.path.join(parent, filename)
      arcname = pathfile[pre_len:].strip(os.path.sep)   # Relative paths 
      zipf.write(pathfile, arcname)
  zipf.close()

2. tar/tar.gz


import os, tarfile
#1 Subpackage the entire root directory. Empty subdirectories are packaged. 
# If only the package is not compressed, will "w:gz" Parameter is changed to "w:" or "w" Can. 
def make_targz(output_filename, source_dir):
  with tarfile.open(output_filename, "w:gz") as tar:
    tar.add(source_dir, arcname=os.path.basename(source_dir))
# Add file packaging one by one, unpacked empty subdirectories. Filterable files. 
# If only the package is not compressed, will "w:gz" Parameter is changed to "w:" or "w" Can. 
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):
    for file in files:
      pathfile = os.path.join(root, file)
      tar.add(pathfile)
  tar.close()

More about Python related topics: interested readers to view this site "Python file and directory skills summary", "Python skills summary text file", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article has been helpful to you in Python programming.


Related articles: