Python zipfile – Python ZIP

Python zipfile module helps us in working with zip files. Today we will learn how to read zip archive details, create and extract zip files using zipfile module.

Python zipfile模块可帮助我们处理zip文件。 今天,我们将学习如何读取zip存档详细信息,如何使用zipfile模块创建和提取zip文件。

In case you don’t know, there is a built-in zip() function in Python. You can read all about it at AppDividend Python zip() Tutorial.

如果您不知道,Python中有一个内置的zip()函数。 您可以在AppDividend Python zip()教程中阅读所有相关内容。

Python压缩档 (Python zipfile)

Python zipfile module is important for even production-grade application. This is due to the reason that on servers, files uploaded through web applications are often zipped and then saved to save costly server space. Let’s get started with the zipfile module examples. This python module is also similar to python tarfile module.

Python zipfile模块对于甚至生产级应用程序也很重要。 这是由于以下原因:在服务器上,通常将通过Web应用程序上传的文件压缩后保存,以节省昂贵的服务器空间。 让我们开始使用zipfile模块示例。 这个python模块也类似于python tarfile模块

Please note that for demonstration purposes, we have a ZIP file called Archive.zip with some text files and this ZIP is present in the directory where we run the programs.

请注意, 出于演示目的 ,我们有一个名为Archive.zip的ZIP文件,其中包含一些文本文件,并且该ZIP文件位于运行程序的目录中。

读取一个ZIP文件 (Reading a ZIP file)

We will start with listing files present inside a ZIP Archive. Here is a sample program:

我们将从列出ZIP存档中存在的文件开始。 这是一个示例程序:

import zipfile

zip_archive = zipfile.ZipFile("Archive.zip", "r")

# list file information
for file_info in zip_archive.infolist():
    print(file_info.filename, file_info.date_time, file_info.file_size)

Let’s see the output for this program:

python zipfile infolist

让我们看一下该程序的输出:

We were able to list files present in the Archive and some meta-data for files as well. Please note that the process is really fast as we didn’t have to unzip the file before we could read it.

我们能够列出存档中存在的文件以及文件的一些元数据。 请注意,这个过程确实很快,因为在阅读文件之前我们不必解压文件

创建一个ZIP文件 (Create a ZIP file)

Next, we will start by looking at how a ZIP file can be made (this is how we made it as well). To create a new Archive, we will make an instance of ZipFile with a mode of w. Note that if a file with the same name exists, it will be truncated completely. So, make sure that your file name is unique.

接下来,我们将首先研究如何制作ZIP文件(这也是我们制作的方式)。 为了创建一个新的Archive,我们将创建一个w模式的ZipFile实例。 请注意,如果存在相同名称的文件,它将被完全截断。 因此,请确保您的文件名是唯一的。

Let’s look at the code snippet to create a zip file using the zipfile module:

让我们看一下使用zipfile模块创建一个zip文件的代码片段:

import zipfile

archive = zipfile.ZipFile('Archive.zip', mode='w')
try:
    archive.write('hello.txt')
    archive.write('second.txt')
    print('Files added.')
finally:
    print('Reading files now.')
    archive.close()

zip_archive = zipfile.ZipFile("Archive.zip", "r")

# list file information
for file_info in zip_archive.infolist():
    print(file_info.filename, file_info.date_time, file_info.file_size)

Let’s see the output for this program:

zipfile create zip file

让我们看一下该程序的输出:

检查有效的ZIP文件 (Checking for a Valid ZIP file)

We can also test if a mentioned file is a valid ZIP Archive. Here is a sample program:

我们还可以测试所提及的文件是否为有效的ZIP存档。 这是一个示例程序:

import zipfile

test_files = ['check_if_zipfile.py', 'Archive.zip']

for file in test_files:
    print('ZIP status for {0}: {1}'.format(file, zipfile.is_zipfile(file)))

Let’s see the output for this program:

python zipfile is_zipfile

This is an important test to be performed while handling ZIP Archives.

让我们看一下该程序的输出:

这是处理ZIP存档时要执行的重要测试。

解压缩ZIP存档 (Unzipping a ZIP Archive)

Let’s look at a code snippet:

让我们看一下代码片段:

import zipfile

print('Extracting ZIP.')
archive = zipfile.ZipFile('Archive.zip', 'r')

# Extract to current directory
archive.extractall('.')
print('ZIP Extracted.')

archive.close()

Let’s see the output for this program:

python zipfile extractall

Note that a new directory isn’t made, rather, files are put in same directory here. Mention a directory if you want to put files at a particular location.

让我们看一下该程序的输出:

请注意,不会创建新目录,而是将文件放在此处的同一目录中。 如果要将文件放在特定位置,请提及目录。

使用其他名称将文件添加到ZIP (Adding a file to ZIP with different name)

It is possible to add member files into an archive with a different name. Here is a sample program to show how this can be done:

可以使用其他名称将成员文件添加到存档中。 这是一个示例程序,显示了如何完成此操作:

import zipfile

print('Creating Archive.zip.')
archive = zipfile.ZipFile('Archive.zip', mode='w')
try:
    archive.write('hello.txt', arcname='some_hello.txt')
    archive.write('second.txt', arcname='another.txt')
finally:
    archive.close()

print('ZIP created with different name.')

Let’s see the output for this program:

python zipfile write with different file name

让我们看一下该程序的输出:

结论 (Conclusion)

In this Python zipfile tutorial, we saw how we can create ZIP archives and read them. Use this module to produce Zipped files and process them as required.

在此Python zipfile教程中,我们了解了如何创建ZIP档案并进行阅读。 使用此模块可以生成压缩文件并根据需要对其进行处理。

Reference: API Doc

参考API文档

翻译自: https://www.journaldev.com/19002/python-zipfile-zip

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值