Home > Backend Development > Python Tutorial > How to use the zipfile compression package module in Python

How to use the zipfile compression package module in Python

PHPz
Release: 2023-04-20 14:22:06
forward
2386 people have browsed it

Introduction

The ZIP file format is a commonly used archiving and compression standard. zipfile The module provides tools to create, read, write, add and list ZIP files

This module currently cannot handle split-volume ZIP files. It supports decrypting encrypted files in ZIP archives, but it cannot currently create an encrypted file. Decryption is very slow because it is implemented using native Python instead of C

Compressed files

class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64 =True, compresslevel=None, *, strict_timestamps=True):ZipFile object, compression specifies the compression mode

ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None ): Write a compressed file, filename is the original file name, arcname is the archive file name, compress_type specifies the compression mode

Compression mode Meaning
ZIP_STORED No compression, default value
ZIP_DEFLATED Commonly used ZIP compression
ZIP_BZIP2 BZIP2 compression
ZIP_LZMA LZMA compression

The code is as follows:

import random

import zipfile

with open('1.txt', mode='w') as f:

    for _ in range(1000):

        f.write(str(random.random()) + '\n')

with zipfile.ZipFile('1.zip', mode='w', compression=zipfile.ZIP_DEFLATED) as zf:

    zf.write('1.txt')

    zf.write('1.txt', '2.txt', zipfile.ZIP_STORED)  # 原文件名1.txt,存为2.txt,不压缩
Copy after login

Effect

How to use the zipfile compression package module in Python

Decompress the file

ZipFile.namelist(): Return File list sorted by name

ZipFile.extract(member, path=None, pwd=None): Extract the file to the specified directory

import zipfile

with zipfile.ZipFile('1.zip') as zf:

    for filename in zf.namelist():

        zf.extract(filename, '.')
Copy after login

Whether it is a ZIP file

Call zipfile.is_zipfile(filename)

is a valid ZIP file and returns True, otherwise it returns False, not at all Existence returns False

import zipfile

for filename in ['1.txt', '1.zip', '2.zip']:

    print(filename, zipfile.is_zipfile(filename))

    # 1.txt False

    # 1.zip True

    # 2.zip False
Copy after login

Read metadata

ZipFile.namelist(): Returns a list of files sorted by name

ZipFile.getinfo(name): Return a ZipInfo object

import zipfile

with zipfile.ZipFile('1.zip', 'r') as zf:

    print(zf.namelist())  # 文件列表

    for info in zf.infolist():

        print(info)

        print(info.filename)  # 文件名称

        print(info.date_time)  # 修改时间,可用datetime.datetime(*info.date_time)

        print(info.compress_type)  # 压缩类型,值为zipfile.ZIP_STORED、ZIP_DEFLATED、ZIP_BZIP2、ZIP_LZMA

        print(info.comment)  # 注释

        print(info.extra)  # 扩展字段数据

        print(info.create_system)  # 创建所用系统,0为Windows,3为Unix

        print(info.create_version)  # 创建所用PKZIP版本

        print(info.extract_version)  # 提取所用PKZIP版本

        print(info.flag_bits)  # 标志位

        print(info.volume)  # 文件头的分卷号

        print(info.compress_size)  # 已压缩的数据大小

        print(info.file_size)  # 未压缩的数据大小

        print()
Copy after login

Compress files from other data sources

ZipFile.writestr(zinfo_or_arcname, data, compress_type= None, compresslevel=None): Write a file to the compressed file

import random

import zipfile

data = ''.join([str(random.random()) + '\n' for i in range(1000)])

with zipfile.ZipFile('1.zip', mode='w', compression=zipfile.ZIP_DEFLATED) as zf:

    zf.writestr('1.txt', data)
Copy after login

Write to ZipInfo

class zipfile.ZipInfo(filename='NoName', date_time=( 1980, 1, 1, 0, 0, 0)): Compressed file member information class

import time

import random

import zipfile

data = ''.join([str(random.random()) + '\n' for i in range(1000)])

with zipfile.ZipFile('1.zip', mode='w', compression=zipfile.ZIP_DEFLATED) as zf:

    info = zipfile.ZipInfo('1.txt', date_time=time.localtime(time.time()))

    info.compress_type = zipfile.ZIP_DEFLATED

    info.comment = b'a comment'

    info.create_system = 0

    zf.writestr(info, data)
Copy after login

Effect

How to use the zipfile compression package module in Python

Append file

Change the mode of ZipFile to append mode a

import random

import zipfile

with open('2.txt', mode='w') as f:

    for _ in range(1000):

        f.write(str(random.random()) + '\n')

with zipfile.ZipFile('1.zip', mode='a') as zf:

    zf.write('2.txt')
Copy after login

Create a ZIP containing the Python library

class zipfile.PyZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, optimize=-1): Used to create a ZIP class containing the Python library

zipfile_pyzipfile.py

import sys

import zipfile

with zipfile.PyZipFile('pyzipfile.zip', mode='w') as zf:

    zf.debug = 3

    zf.writepy('.')

for name in zf.namelist():

    print(name)

sys.path.insert(0, 'pyzipfile.zip')

import zipfile_pyzipfile

print('Imported from:', zipfile_pyzipfile.__file__)
Copy after login

The above is the detailed content of How to use the zipfile compression package module in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template