简体   繁体   中英

Python gzip folder structure when zipping single file

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.

You must use gzip.GzipFile and supply a fileobj . If you do that, you can specify an arbitrary filename for the header of the gz file.

Why not just open the file without specifying a directory hierarchy (just do gzip.open("file.txt.gz"))?. Seems to me like that works. You can always copy the file to another location, if you need to.

If you set your current working directory to your output folder, you can then call gzip.open("file.txt.gz") and the gz file will be created without the hierarchy

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM