Table of Contents
Introduction
Decompress the file
Whether it is a ZIP file
Read metadata
Compress files from other data sources
Write to ZipInfo
Append file
Create a ZIP containing the Python library
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

Apr 20, 2023 pm 02:22 PM
python zipfile

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!

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

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles