Python压缩单个文件时的gzip文件夹结构

4

我正在使用Python的gzip模块对单个文件进行压缩,使用类似文档中示例的代码:

import gzip
content = "Lots of content here"
f = gzip.open('/home/joe/file.txt.gz', 'wb')
f.write(content)
f.close()

如果我在7-zip中打开gz文件,我会看到一个文件夹层次结构,与我写入gz的路径匹配,并且我的内容嵌套在几个文件夹中,例如上面的示例中的/home/joe或Windows中的C:->文档和设置->等等。
如何让我压缩的一个文件只出现在gz文件的根目录中?
4个回答

10

看起来你需要直接使用GzipFile

import gzip
content = "Lots of content here"
real_f = open('/home/joe/file.txt.gz', 'wb')
f = gzip.GZipFile('file.txt.gz', fileobj=real_f)
f.write(content)
f.close()
real_f.close()

看起来 open 不允许你将 fileobj 与文件名分开指定。


你有任何想法为什么会出现这个错误吗?AttributeError: 'module' object has no attribute 'GZipFile' - Ishan Liyanage
请尝试使用GzipFile。 - BML91

2

您必须使用gzip.GzipFile并提供一个fileobj。如果这样做,您可以为gz文件的头部指定任意文件名。


你有任何想法为什么会出现这个错误吗?AttributeError: 'module' object has no attribute 'GZipFile'。 - Ishan Liyanage
@IshanLiyanage:Python 2 还是 3? - Aaron Digulla
这是Python 2版本,但我通过在与Python脚本相同的目录中创建gz文件并将其移动到正确位置来解决了这个问题。 - Ishan Liyanage

0
如果你将当前工作目录设置为输出文件夹,然后调用gzip.open("file.txt.gz"),那么gz文件将被创建而无需层级结构。
import os
import gzip
content = "Lots of content here"
outputPath = '/home/joe/file.txt.gz'
origDir = os.getcwd()
os.chdir(os.path.dirname(outputPath))
f = gzip.open(os.path.basename(outputPath), 'wb')
f.write(content)
f.close()
os.chdir(origDir)

0

为什么不直接打开文件而不指定目录层次结构(只需gzip.open(“file.txt.gz”))?这对我来说似乎可以。如果需要,您始终可以将文件复制到另一个位置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接