ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python2.7 zipfile 的简单用法

2020-05-23 09:56:10  阅读:9  来源: 互联网

标签:zip zipfile python2.7 用法 zipfilename file path os


简要说明使用python 进行 zip 文件压缩和解压缩的方法

1 代码示例

#! /usr/bin/env python
#  -*- coding: UTF-8 -*-
import zipfile
import os


def decompress_file(zip_file_path):
    """
    解压文件到某个目录
    :param zip_file_path:    待解压的zip 文件路径
    :return:
    """
    with zipfile.ZipFile(zip_file_path, 'r') as z:
        # 解压全部
        z.extractall('./zipfile')


def compress_file(zipfilename, dirname):
    """
    压缩某个目录下的所有文件
    :param zipfilename:    压缩文件的路径
    :param dirname:        待压缩的目录
    :return:
    """
    if os.path.isfile(dirname):
        with zipfile.ZipFile(zipfilename, 'w') as z:
            z.write(dirname)
    else:
        with zipfile.ZipFile(zipfilename, 'w') as z:
            for root, dirs, files in os.walk(dirname):
                for singlefile in files:
                    if singlefile != zipfilename:
                        filepath = os.path.join(root, singlefile)
                        z.write(filepath)


def check_zipfile_list(zip_file_path):
    """
    查看zip 压缩文件中的文件列表
    :param zip_file_path:    zip 压缩文件的路径
    :return:
    """
    if not os.path.exists(zip_file_path) and os.path.isfile(zip_file_path):
        return
    with zipfile.ZipFile(zip_file_path, 'r') as z:
        print z.namelist()


def add_file(zipfilename, addfile):
    """
    添加文件到压缩文件
    :param zipfilename:    已存在的zip 压缩文件路径
    :param addfile:        待添加到zip 压缩文件中的文件路径
    :return:
    """
    if os.path.isfile(addfile):
        with zipfile.ZipFile(zipfilename, 'a') as z:
            z.write(addfile)


if __name__ == '__main__':
    # add_file('./testdata/1.zip', './testdata/2.txt')
    # check_zipfile_list('./testdata/1.zip')
    # decompress_file('./testdata/1.zip')
    compress_file('testdata.zip', './testdata')

标签:zip,zipfile,python2.7,用法,zipfilename,file,path,os
来源: https://www.cnblogs.com/gaozhidao/p/12941160.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有