English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This example describes how to package folders using Python. Share it with everyone for reference, as follows:
Section 1: zip
import os, zipfile #Pack the directory into a 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 path zipf.write(pathfile, arcname) zipf.close()
Section 2: tar/tar.gz
import os, tarfile #Pack the entire root directory at once. Empty subdirectories will be packed. # If you only want to package without compression, you can change the "w:gz" parameter to "w:" or "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)) # Add files one by one for packaging, do not package empty subdirectories. Files can be filtered. # If you only want to package without compression, you can change the "w:gz" parameter to "w:" or "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()
Readers who are interested in more content related to Python can check the special topics on this site: 'Summary of Python File and Directory Operation Skills', 'Summary of Python Text File Operation Skills', 'Summary of Python URL Operation Skills', 'Summary of Python Image Operation Skills', 'Python Data Structures and Algorithms Tutorial', 'Summary of Python Socket Programming Skills', 'Summary of Python Function Usage Skills', 'Summary of Python String Operation Skills', and 'Classic Tutorial of Python入门与进阶入门与进阶'.
I hope the content described in this article will be helpful to everyone in designing Python programs.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been edited by humans, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)