python2.7 zipfile 的简单用法
作者:互联网
简要说明使用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