美文网首页
python zip 压缩 zipfile

python zip 压缩 zipfile

作者: book_02 | 来源:发表于2021-03-11 20:10 被阅读0次

    封装成函数如下:

    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')
    

    相关文章

      网友评论

          本文标题:python zip 压缩 zipfile

          本文链接:https://www.haomeiwen.com/subject/lqpoqltx.html