压缩单个文件时的Python gzip文件夹结构 [英] Python gzip folder structure when zipping single file

查看:134
本文介绍了压缩单个文件时的Python gzip文件夹结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python的gzip模块为单个文件gzip内容,并使用类似于文档中示例的代码:

  import gzip 
content =此处有很多内容
f = gzip.open('/ home / joe / file.txt.gz','wb')
f.write(内容)
f.close()

如果我打开7-zip中的gz文件,我看到一个文件夹层次结构,该层次结构与我写入gz的路径匹配,并且我的内容嵌套在多个文件夹的深处,例如上例中的/ home / joe,或Windows中的C:-> Documents and Settings->etc。 >

我如何将要压缩的一个文件放在gz文件的根目录中?

解决方案

看来您将不得不直接使用 GzipFile

  import gzip 
content =此处有很多内容
real_f = open('/ home / joe / file.txt.gz','wb')
f = gzip.GZipFile('file.txt.gz',fileobj = real_f)
f.write(内容)
f.close()
real_f.close()

似乎 open 不允许您指定 fileobj 与文件名分开。


I'm using Python's gzip module to gzip content for a single file, using code similar to the example in the docs:

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

If I open the gz file in 7-zip, I see a folder hierarchy matching the path I wrote the gz to and my content is nested several folders deep, like /home/joe in the example above, or C: -> Documents and Settings -> etc in Windows.

How can I get the one file that I'm zipping to just be in the root of the gz file?

解决方案

It looks like you will have to use GzipFile directly:

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()

It looks like open doesn't allow you to specify the fileobj separate from the filename.

这篇关于压缩单个文件时的Python gzip文件夹结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆