Loading

typing模块


zipfile压缩解压缩

形参 mode 应当为 'r' 来读取一个存在的文件,'w' 来截断并写入新的文件, 'a' 来添加到一个存在的文件。ZipFile 也是一个上下文管理器,也支持with语句。解压时可指定密码,密码必须是bytes类型。

import zipfile

# 压缩
z = zipfile.ZipFile('t.zip', 'w')  # t.zip表示压缩后的文件名
z.write('a.log')  # 要打包压缩的文件
z.write('data.data')
z.close()  # 关闭文件

# 解压
z = zipfile.ZipFile('laxi.zip', 'r')  # 要解压的文件
z.extract()  # 解压单个文件。
z.extractall(path='.')  # 解压的路径
z.close()

使用with语句:

with zipfile.ZipFile('t1.zip','w') as f:
    f.write('a.txt')
    
with zipfile.ZipFile('t1.zip','r') as f:
    f.extractall(path='.',pwd='123'.encode('utf-8'))

tarfile压缩解压缩

import tarfile

# 压缩
t=tarfile.open('/tmp/egon.tar','w')
t.add('/test1/a.py',arcname='a.bak')
t.add('/test1/b.py',arcname='b.bak')
t.close()


# 解压
t=tarfile.open('/tmp/egon.tar','r')
t.extractall('/egon')
t.close()

压缩或解压缩源文件都不会删除。

案例

穷举破解一个6位以内的纯数字密码。

import zipfile
import time

def extract(path):
    start_time = time.time()
    for p in range(1000000):
        try:
            zfile = zipfile.ZipFile(path,'r')
            zfile.extractall(path='.',pwd=str(p).encode('utf-8'))
            print(f'总耗时{time.time() - start_time}')
            return f'密码为:{p}'
        except Exception:
            print(f'尝试密码{p}')

print(extract('test.zip'))

posted @ 2021-01-13 15:27  吃了好多肉  阅读(105)  评论(0编辑  收藏  举报