封装成函数如下:
zip_add_dir
添加目录到压缩文件
zip_add_file
添加文件到压缩文件
zip_add_files
添加多个文件到压缩文件
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import zipfile
def zip_add_dir(source_dir, output_filename):
zipf = zipfile.ZipFile(output_filename, 'a')
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()
def zip_add_file(filename, output_filename):
zipf = zipfile.ZipFile(output_filename, 'a')
zipf.write(filename)
zipf.close()
def zip_add_files(file_list, output_filename):
zipf = zipfile.ZipFile(output_filename, 'a')
for filename in file_list:
zipf.write(filename)
zipf.close()
zip_name = 'test.zip'
zip_add_dir('config', zip_name)
zip_add_dir('include', zip_name)
zip_add_file('txxx.dll', zip_name)
zip_add_files(['a.txt', 'b.txt'], zip_name)
os.system('pause')
网友评论