首页 > 技术文章 > 压缩模块

os-linux 2019-11-28 16:05 原文

Python压缩文件

在py2和py3中对文件进行解压缩稍有不同。

  • shutil 模块【压缩支持py2和py3,解压只支持py3】
  • tarfile / zipfile模块【支持py2和py3】
import shutil

# 文件压缩
ret = shutil.make_archive(
    base_name="code/www",  # 压缩包文件路劲
    format='zip',  # “zip”, “tar”
    root_dir='code/fuck'  # 被压缩的文件件
)
print(ret)

# 解压文件
shutil._unpack_zipfile('code/www.zip', 'code/new')
shutil._unpack_tarfile('code/www.tar', 'code/new')

import zipfile

# 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()

# 解压
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall()
z.close()
import tarfile

# 压缩
tar = tarfile.open('your.tar', 'w')
tar.add('utils/codes/luffycity/a1.py')
tar.add('utils/codes/luffycity/a3.py')
tar.close()

# 解压
tar = tarfile.TarFile('code/www.tar', 'r')
tar.extractall(path='/code/x1/')  # 可设置解压地址
tar.close()

推荐阅读