zipfile模块的基本使用

1. 解压zip文件

import os
import zipfile
file = r"E:\testdir\test01\icomoon.zip"
z = zipfile.ZipFile(file)
print(z.filename)
print(z.namelist())   # 返回文件名列表
print(z.infolist())  # 返回压缩包中的文件对象列表

# 解压单个文件到指定的目录
# 方法一:
z.extract(z.namelist()[1],r'E:\testdir\test01')
z.extract(z.namelist()[2],r'E:\testdir\test01')
z.extract(z.namelist()[3],r'E:\testdir\test01')

# 方法二:
data = z.read('selection.json')
with open(r'E:\testdir\test01\icomoon.json','wb') as f:
 f.write(data)
z.close()

2. 压缩文件

# 给压缩文件中添加文件
file = r"E:\testdir\test01\common.zip"
z = zipfile.ZipFile(file,"w")

# arcname代表重命名,路径中的testdir目录就不会在压缩包中出现
z.write(r'E:\testdir\runtask_common.py',arcname='runtask_common.py',compress_type=zipfile.ZIP_DEFLATED)
# z.write(r'E:\testdir\学院.html',arcname='学院.html',compress_type=zipfile.ZIP_DEFLATED)
# z.write(r'E:\testdir\考试结果.html',arcname='考试结果.html',compress_type=zipfile.ZIP_DEFLATED)

z.write(r'E:\testdir\runtask_common.py',compress_type=zipfile.ZIP_DEFLATED)
z.write(r'E:\testdir\学院.html',compress_type=zipfile.ZIP_DEFLATED)
z.write(r'E:\testdir\考试结果.html',arcname='考试结果.html',compress_type=zipfile.ZIP_DEFLATED)
z.close()

3.向zip中追加文件

# 向zip文件中追加文件
file = r"E:\testdir\test01\common01.zip"
z = zipfile.ZipFile(file,"a")
z.write(r'E:\testdir\学院.html',compress_type=zipfile.ZIP_DEFLATED)
z.close()

4.解压所有文件到指定的目录

def extractall_file(zip_filename,dst_dir):
 """
 解压所有的文件到指定的目录
 :param zip_filename: 要解压的压缩包文件路径
 :param dst_dir: 解压的目录
 :return:
 """
 z = zipfile.ZipFile(zip_filename)
 members = [i.encode("cp437").decode("gbk") for i in z.namelist()]
 print('members:',members)
 z.extractall(dst_dir)
 z.close()
 for dirpath, dirnames, filenames in os.walk(r"E:\testdir\test02"):
  for i in filenames:
   os.rename(os.path.join(dirpath,i),os.path.join(dirpath,i.encode("cp437").decode("gbk")))

5.破译一个六位数的zip压缩包密码

def main(zip_filename):
 """
 破译密码,并将文件解压
 zip_filename: 需要破译的zip文件名
 :return:
 """
 # 先生成一个6位数的密码文件
 fs = open('passwd.txt','w')
 for i in range(1000000):
  fs.write(f'{i}'.rjust(6,'0')+'\n')
 fs.close()
 z = zipfile.ZipFile(zip_filename)
 ext_path= os.path.dirname(__file__)
 # z.extractall(r'E:\testdir\test02', pwd='123456'.encode('utf-8'))
 with open('passwd.txt') as fs:
  for i in fs:
   try:
    z.extractall(ext_path,pwd=f'{i.strip()}'.encode('utf-8'))
    passwd = i
    break
   except:
    pass
  print(f"密码为:{passwd}")
 z.close()

6.压缩

import zipfile
import os


def yasuo(zippath,path):
    """

    :param zippath: 压缩后的压缩包名称
    :param path: 被压缩的文件路径
    :return:
    """

    z = zipfile.ZipFile(file=zippath,mode='w',compression=zipfile.ZIP_DEFLATED)

    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            # 文件路径
            res_path = str(os.path.join(dirpath,filename))
            # arcname的归档路径
            rename_path = str(os.path.join(dirpath,filename))[len(path)+1:]
            print(res_path,rename_path)
            z.write(res_path,arcname=rename_path)
    z.close()

file = r'E:\testdir\test02'
yasuo(r'E:\testdir\laowang.zip', file)

你可能感兴趣的:(python,python,开发语言)