search
HomeBackend DevelopmentPython TutorialHow to use the zipfile compression package module in Python

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,不压缩

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, '.')

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

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()

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)

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)

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')

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__)

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

What is NumPy, and why is it important for numerical computing in Python?What is NumPy, and why is it important for numerical computing in Python?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Discuss the concept of 'contiguous memory allocation' and its importance for arrays.Discuss the concept of 'contiguous memory allocation' and its importance for arrays.May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)