Python Packaging Folder Method summary (zip,tar,tar.gz, etc.)

Source: Internet
Author: User

The examples in this article describe how Python packs folders. Share to everyone for your reference, as follows:

One, zip

?
1234567891011 import os, zipfile#打包目录为zip文件(未压缩)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)   #相对路径      zipf.write(pathfile, arcname)  zipf.close()

Second, tar/tar.gz

?
123456789101112131415 import os, tarfile#一次性打包整个根目录。空子目录会被打包。#如果只打包不压缩,将"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.basename(source_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):    for file in files:      pathfile = os.path.join(root, file)      tar.add(pathfile)  tar.close()

More interested in Python related content readers can view this site topic: "Python File and directory Operation skills Summary", "Python text file Operation tips Summary", "Python URL operation tips Summary", "Python Picture Operation skills Summary", " Python data structure and algorithm tutorial, Python socket Programming Tips Summary, Python function tips Summary, python string manipulation tips summary, and Python introductory and advanced classic tutorials

Method Summary of the Python Packaging folder (zip,tar,tar.gz, etc.)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.