python中zipfile的使用_如何在Python中使用ZIPFILE模块压缩文件。
问题
您要在python中创建一个压缩文件。
介绍
ZIP文件可以保存许多其他文件的压缩内容。压缩文件会减小其在磁盘上的大小,这在通过Internet或使用Control-m AFT或Connect direct甚至scp在系统之间进行传输时非常有用。
Python程序使用zipfile模块中的函数创建ZIP文件。
怎么做...
1.我们将使用zipfile和io包。如果系统上缺少任何软件包,请使用pip安装它们。如果不确定,请使用pip Frozen命令验证软件包。
2.我们将编写一个将样本数据写入文件的功能。下面的函数write_data_to_files将数据作为输入,并在当前目录名称中创建一个文件。
示例# Function : write_data_to_files
def write_data_to_files(inp_data, file_name):
"""
function : create a csv file with the data passed to this code
args : inp_data : data to be written to the target file
file_name : target file name to store the data
return : none
assumption : File to be created and this code are in same directory.
"""
print(f" *** Writing the data to - {file_name}")
throwaway_storage = io.StringIO(inp_data)
with open(file_name, 'w') as f:
for line in throwaway_storage:
f.write(line)
3.现在,我们将编写一个函数file_compress来压缩在上述步骤中创建的文件。此功能接受文件列表,遍历文件并将其压缩为zip文件。注释中提供了每个步骤的详细说明。
要创建自己的压缩ZIP文件,您必须通过将第二个参数'w'传递给写模式来打开ZipFile对象。
当您将路径传递给write()ZipFile对象的方法时,Python会在该路径上压缩文件并将其添加到ZIP文件中。
write()method的第一个参数是要添加的文件名的字符串。
第二个参数是压缩类型参数-告诉计算机应使用哪种算法压缩文件。
示例# Function : file_compress
def file_compress(inp_file_names, out_zip_file):
"""
function : file_compress
args : inp_file_names : list of filenames to be zipped
out_zip_file : output zip file
return : none
assumption : Input file paths and this code is in same directory.
"""
# Select the compression mode ZIP_DEFLATED for compression
# or zipfile.ZIP_STORED to just store the file
compression = zipfile.ZIP_DEFLATED
print(f" *** Input File name passed for zipping - {inp_file_names}")
# create the zip file first parameter path/name, second mode
print(f' *** out_zip_file is - {out_zip_file}')
zf = zipfile.ZipFile(out_zip_file, mode="w")
try:
for file_to_write in inp_file_names:
# Add file to the zip file
# first parameter file to zip, second filename in zip
print(f' *** Processing file {file_to_write}')
zf.write(file_to_write, file_to_write, compress_type=compression)
except FileNotFoundError as e:
print(f' *** Exception occurred during zip process - {e}')
finally:
# Don't forget to close the file!
zf.close()
4.我们将调用函数来创建两个csv文件,然后将其压缩。我们将在一个文件中使用赢得了1以上大满贯冠军的网球运动员数据-temporary_file1_for_zip.csv,在另一个文件中使用获得小于或等于1大满贯的网球运动员的数据suspended_file1_for_zip.csv。然后,我们将这两个文件都压缩为临时文件。
示例import zipfile
import io
import pandas as pd
file_name1 = "temporary_file1_for_zip.csv"
file_name2 = "temporary_file2_for_zip.csv"
file_name_list = [file_name1, file_name2]
zip_file_name = "temporary.zip"
# data for file 1
file_data_1 = """
player,titles
Federer,20
Nadal,20
Djokovic,17
Murray,3
"""
# data for file 2
file_data_2 = """
player,titles
Theim,1
Zverev,0
Medvedev,0
Rublev,0
"""
# write the file_data to file_name
write_data_to_files(file_data_1, file_name1)
write_data_to_files(file_data_2, file_name2)
# zip the file_name to zip_file_name
file_compress(file_name_list, zip_file_name)
示例
5.将以上步骤中讨论的所有内容放在一起。# Define the data
# let us create a zip file with a single file
import zipfile
import io
import pandas as pd
# Function : write_data_to_files
def write_data_to_files(inp_data, file_name):
"""
function : create a csv file with the data passed to this code
args : inp_data : data to be written to the target file
file_name : target file name to store the data
return : none
assumption : File to be created and this code are in same directory.
"""
print(f" *** Writing the data to - {file_name}")
throwaway_storage = io.StringIO(inp_data)
with open(file_name, 'w') as f:
for line in throwaway_storage:
f.write(line)
# Function : file_compress
def file_compress(inp_file_names, out_zip_file):
"""
function : file_compress
args : inp_file_names : list of filenames to be zipped
out_zip_file : output zip file
return : none
assumption : Input file paths and this code is in same directory.
"""
# Select the compression mode ZIP_DEFLATED for compression
# or zipfile.ZIP_STORED to just store the file
compression = zipfile.ZIP_DEFLATED
print(f" *** Input File name passed for zipping - {inp_file_names}")
# create the zip file first parameter path/name, second mode
print(f' *** out_zip_file is - {out_zip_file}')
zf = zipfile.ZipFile(out_zip_file, mode="w")
try:
for file_to_write in inp_file_names:
# Add file to the zip file
# first parameter file to zip, second filename in zip
print(f' *** Processing file {file_to_write}')
zf.write(file_to_write, file_to_write, compress_type=compression)
except FileNotFoundError as e:
print(f' *** Exception occurred during zip process - {e}')
finally:
# Don't forget to close the file!
zf.close()
# __main__ program
if __name__ == '__main__':
# Define your file name and data
file_name1 = "temporary_file1_for_zip.csv"
file_name2 = "temporary_file2_for_zip.csv"
file_name_list = [file_name1, file_name2]
zip_file_name = "temporary.zip"
file_data_1 = """
player,titles
Federer,20
Nadal,20
Djokovic,17
Murray,3
"""
file_data_2 = """
player,titles
Theim,1
Zverev,0
Medvedev,0
Rublev,0
"""
# write the file_data to file_name
write_data_to_files(file_data_1, file_name1)
write_data_to_files(file_data_2, file_name2)
# zip the file_name to zip_file_name
file_compress(file_name_list, zip_file_name)*** Writing the data to - temporary_file1_for_zip.csv
*** Writing the data to - temporary_file2_for_zip.csv
*** Input File name passed for zipping - ['temporary_file1_for_zip.csv', 'temporary_file2_for_zip.csv']
*** out_zip_file is - temporary.zip
*** Processing file temporary_file1_for_zip.csv
*** Processing file temporary_file2_for_zip.csv
输出结果
执行以上代码后,输出为在当前目录中创建了secondary_file1_for_zip.csv。
在当前目录中创建了临时文件2_for_zip.csv。
在当前目录中创建了临时文件。
python中zipfile的使用_如何在Python中使用ZIPFILE模块压缩文件。相关推荐
- python画图修改背景颜色_如何在 Matplotlib 中更改绘图背景的实现
介绍 Matplotlib是Python中使用最广泛的数据可视化库之一.无论是简单还是复杂的可视化项目,它都是大多数人的首选库. 在本教程中,我们将研究如何在Matplotlib中更改绘图的背景. 导 ...
- python 参数个数 同名函数_如何在python中编写不同参数的同名方法
我在Java背景下学习Python(3.x). 我有一个python程序,我在其中创建一个personObject并将其添加到列表中.p = Person("John") list ...
- eval在python中是什么意思_如何在Python中使用eval ?
Python中的 eval是什么? 在Python中,我们有许多内置方法,这些方法对于使Python成为所有人的便捷语言至关重要,而eval是其中一种.eval函数的语法如下: eval(expres ...
- python中奇数怎么表示_如何在python输出数据中的奇数
如何在python输出数据中的奇数 发布时间:2020-07-10 17:08:48 来源:亿速云 阅读:131 这篇文章将为大家详细讲解有关如何在python输出数据中的奇数,文章内容质量较高,因此 ...
- python中while语句是_如何在Python中使用while语句[适合初学者]
while语句是重复循环的语句,那么如何用Python编写,下面Gxl网就带领大家来学习一下Python中使用while语句.[推荐阅读:Python视频教程] 一:什么是while语句?Python ...
- python实现随机抽取答题_如何在python中实现随机选择
这篇文章主要介绍了如何在python中实现随机选择,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 想从一个序列中随机抽取若干元素,或者想生成几个随机 ...
- python二进制转八进制代码_如何在python中输入二进制、八进制、十进制、十六进制数据并转换...
最近在学习python,不过跟着课本的作业题目: 分别就计算二进制110110011.八进制256和十六进制的数字a4b5,并转化为十进制求和. 不过写过程中遇到了个问题: 如何在python中输入二 ...
- python怎么去掉换行符_如何在Python中删除尾部换行符?
如何在Python中删除尾部换行符? 什么是Perl的chomp函数的Python等价物,如果它是换行符,它会删除字符串的最后一个字符? 26个解决方案 1473 votes 尝试方法lstrip() ...
- 用python画奔驰的标志_如何在CATIA中快速画一个奔驰车标
原标题:如何在CATIA中快速画一个奔驰车标 咱们这个公众号呀,总是发一些二次开发啊,代码啊什么的,这观众看的啊,是云里雾里的!哎,内位说了:您能不能讲点儿我们听的懂的内容啊?那好,今儿咱们就来说说, ...
最新文章
- Sigma Function LightOJ - 1336[约数和定理]
- 想找首歌来表达心情!
- mysql处理时间_MYSQL时间处理 (转)
- 管理员获得所有权_在Windows 7中获得注册表项的所有权
- Outlook2016未读邮件怎么设置字体颜色
- 后续:为LAMP添加XCache加速。
- 链表相关的面试题型总结
- 计算机二级考试C语言编程解读:统计N名学生的成绩
- Android更改开机画面
- 判断二极管导通例题_从120分到140分:高考数学解答题五大答题策略
- PeopleSoft
- 屠龙勇士最后都变成了恶龙吗?是!不然你以为恶龙是哪来的?
- python自定义cmap_python自定义cmap_Python matplotlib的使用并自定义colormap的方法
- 分销商城系统开发应用概述详解
- Real-Time Rendering 第二章 渲染管线
- Swagger UI 与 Spring Boot 的集成
- 【Vue】Vue全家桶(九)Vue3
- 一头扎进Shiro-自定义Realm
- c语言图形程序设计 pdf,Visual C++图形程序设计 PDF扫描版[29MB]
- 光盘属于计算机软件,计算机基础知识光盘的概念