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 zipfilezip_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:

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

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 zipfilearchive = 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:

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

检查有效的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 zipfiletest_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:

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 zipfileprint('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:

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 zipfileprint('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:

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

结论 (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

Python zipfile – Python ZIP相关推荐

  1. Python zipfile:高效处理 ZIP 文件(翻译)

    zipfile 可以很方便地读取.写入.提取zip文件.如果在日常工作中经常需要将某些文件打包到zip,不妨试试用它实现一定程度的自动化办公.另外 Python 的 Zip imports 也是一个有 ...

  2. python:zipfile --- 使用ZIP存档

    python:zipfile --- 使用ZIP存档 ZipFile 对象 Path 对象 PyZipFile 对象 ZipInfo 对象 命令行接口 命令行选项 解压缩的障碍 由于文件本身 文件系统 ...

  3. python zipfile压缩_Python压缩模块zipfile实现原理及用法解析

    一.python压缩模块简介 python直接通过内置压缩模块可以直接进行压缩文件的创建: 内置模块 zipfile/rarfile 完成压缩文件的操作. 二. zipfile模块基础使用 2.1 对 ...

  4. python基础教程zip密码_python基础教程Python实现加密的RAR文件解压的方法(密码已知)...

    博主之前在网上找了很多资料,发现rarfile库不能直接调用,需要安装unrar模块,下面将详细介绍整个实现流程. 第一步:安装unrar模块,直接pip install unrar可能会找不到库,需 ...

  5. python zipfile教程_Python中zipfile压缩文件模块的基本使用教程

    zipfile Python 中 zipfile 模块提供了对 zip 压缩文件的一系列操作. f=zipfile.ZipFile("test.zip",mode="&q ...

  6. ksd文件怎么导入存档_DAY5-step5 Python 示例说明 ZIP 压缩文件

    Python使您可以快速创建zip或者tar压缩文档. 以下命令将压缩整个目录 shutil.make_archive(output_filename, 'zip', dir_name) 以下命令使您 ...

  7. python zipfile模块学习笔记(一)

    ZIP文件格式是一种常见的存档和压缩标准,这个zipfile模块提供了工具来创建.读取.写入.附加和列出一个ZIP文件.使用ZIP64扩展(即压缩文件大小超过4G),它能解压加密的ZIP文件,解密过程 ...

  8. python解压zip文件_python怎样压缩和解压缩ZIP文件(转)

    有时我们需要在 Python 中使用 zip 文件,而在1.6版中,Python 就已经提供了 zipfile 模块可以进行这样的操作.不过 Python 中的 zipfile 模块不能处理多卷的情况 ...

  9. python zipfile压缩文件夹

    在使用python zipfile模块进行压缩文件创建的时候,发现貌似只有zipfile对象的write()方法对文件的添加,那么如何将一个文件夹压缩添加到压缩文件中呢? ①直接write() dir ...

最新文章

  1. keytool生成证书_创建自签名ssl证书,Java生产jks证书
  2. 数学不好的人可以学python吗_哪些人适合学金融工程专业 数学不好能学吗
  3. Class类 获取Class对象
  4. quratz数据存储
  5. CompletableFuture详解~异常处理
  6. DSP SRIO接口设计
  7. HDFS副本存放机制
  8. 华为机试练习(十二)叠积木
  9. Unexpected token o in JSON at position 1 at JSON.parse (anonym)
  10. 人类一败涂地human fall flat游戏通关图文攻略
  11. 命令行quser logoff
  12. React.Component
  13. 功能覆盖率实验第二讲:coverage中at_leat用法
  14. 马尔科夫链的一个应用实例
  15. 【2012.10.13 上周工作总结】
  16. 百度杯”CTF比赛(十一月场)
  17. 测试用例模板(个人习惯使用)
  18. 问题 A: 相约HNUST
  19. 两地控制的项目要求_两地控制电动机要求
  20. 图像增强常用评价标准——峰值信噪比、结构相似度

热门文章

  1. 软件工程课程设计团队项目总结与项目报告
  2. 获取公网ip,获取用户城市地址
  3. Perl Fork的问题
  4. 那一次,我们属于彼此
  5. 在Fedora上搭建GTK+的开发环境
  6. memcpy的用法与strcpy的区别及纯c语言实现
  7. python3怎么安装opencv_Python:即使安装了opencv,也无法导入cv2(如何为python3安装opencv3)...
  8. @entity 不限字节长度的类型_面试常考,项目易错,长文详解C/C++中的字节对齐...
  9. C++ Licence认证用于项目开发和设备认证
  10. navacate连接不上mysql_解决navicat连接不上mysql服务器