您的位置:首页 > 编程语言 > Python开发

Python压缩zip文件

2020-08-31 21:18 2131 查看

Python压缩zip文件

自己找了下网上的各种教程,分两种

  • 一条简单的语句,直接压缩,最后生成的压缩包里边包含了压缩文件所在的各级文件夹
  • 切换工作目录,虽然压缩包中只有文件,没有文件的所在的各级文件夹,但感觉不太合适

然后我去看了下官方文档zipfile官方文档,官方文档的说明如下:

zipfile官方文档
ZipFile.write(filename, arcname=None, compress_type=None)
Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry. The archive must be open with mode ‘w’, ‘x’ or ‘a’.

谷歌翻译之后是这样的:

zipfile官方文档—谷歌翻译版
ZipFile.write(文件名,弧名=无,compress_type =无)
将名为filename的文件写入存档,并为其指定存档名称arcname(默认情况下,该名称与filename相同,但不包含驱动器号,并且删除前导路径分隔符)。 如果给定,compress_type会将给压缩参数的值覆盖给新条目的构造函数。 存档必须以“ w”,“ x”或“ a”模式打开。

简单来讲,下边第第二句代码就够用了,只要加上

arcname
参数就可以指定文件在压缩包中的名字了,但神奇的是找的的教程都是
zip_file.write(file_path)
这样的

# 声明zipfile对象
zip_file = zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_DEFLATED)
# 将文件压缩进去
zip_file.write(filename=file_path, arcname=file)
# 关闭zipfile对象
zip_file.close()

最后附上完整代码

def create_zip(file_dir, zip_name):
"""
压缩文件夹到指定名字
:param file_dir: 待压缩的文件夹
:param zip_name: 压缩后压缩包名字
:return: 0: 压缩包名字不合法; 压缩成功或者压缩包已存在则返回文件路径
"""

# 判断目标压缩包文件名是不是.zip结尾
if len(zip_name) < 4 or ".zip" != zip_name[-4:]:
return 0

# 待压缩文件列表
file_list = os.listdir(file_dir)

# 创建空的zip文件(ZipFile类型)。
# 参数w表示写模式。
# zipfile.ZIP_DEFLATE表示需要压缩,文件会变小。
# ZIP_STORED是单纯的复制,文件大小没变。
zip_file_path = os.path.join(file_dir, zip_name)
if os.path.isfile(zip_file_path):
# 压缩文件已存在
return zip_file_path

# 声明zipfile对象
zip_file = zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_DEFLATED)

# 开始压缩
for file in file_list:
file_path = os.path.join(file_dir, file)
if os.path.isfile(file_path):
zip_file.write(filename=file_path, arcname=file)
zip_file.close()
return zip_file_path

最后的最后多bb一句:问题解决不了的时候就去看看官方文档吧

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: