gpt4 book ai didi

如果压缩扩展名不是 "gzip",则 Python ".gz"模块行为异常

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:52 24 4
gpt4 key购买 nike

我需要使用 gzip 压缩文件模块,但输出文件扩展名可能不是 .gz

看看这个简单的代码:

import gzip
import shutil

input_path = "test.txt"
output_path = input_path + ".gz"

with open(input_path, 'w') as file:
file.write("abc" * 10)

with gzip.open(output_path, 'wb') as f_out:
with open(input_path, 'rb') as f_in:
shutil.copyfileobj(f_in, f_out)

它工作正常。但是,如果我将 ".gz" 替换为 ".gzip",那么我将无法正确打开压缩文件:

Uncompressing not working

我尝试使用 7-Zip 和 WinRar,结果是一样的,即使我重命名文件,错误仍然存​​在。

请问有人知道问题出在哪里吗?

我尝试压缩 bz2lzma ,无论扩展名是什么,它们似乎都能正常工作。

最佳答案

您实际上以这种方式创建了两个版本的文件:

首先,.gz文件:

with gzip.open("test.txt.gz", 'wb') as f_out:
with open("test.txt", 'rb') as f_in:
shutil.copyfileobj(f_in, f_out)

二、.gzip文件:

with gzip.open("test.txt.gzip", 'wb') as f_out:
with open("test.txt", 'rb') as f_in:
shutil.copyfileobj(f_in, f_out)

两者都创建一个 GZIP,其中包含您的 test.txt。唯一的区别是在第二种情况下,test.txt 被重命名为 test.txt.gzip


问题是 gzip.open 的参数实际上有两个目的:gzip 压缩文件的文件名里面文件的文件名(糟糕的设计,恕我直言).

因此,如果您执行 gzip.open("abcd", 'wb') 并写入它,它将创建名为 abcd 的 gzip 存档,其中包含一个名为abcd 里面。

但是,魔法来了:如果文件名以 .gz 结尾,那么它的行为就会不同,例如gzip.open("bla.gz", 'wb') 创建一个名为 bla.gz 的 gzip 存档,其中包含一个名为 bla 的文件。

因此,使用 .gz,您激活了(据我所知,未记录!)魔法,而使用 .gzip,您没有。

关于如果压缩扩展名不是 "gzip",则 Python ".gz"模块行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48488342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com