Python gzip folder structure when zipping a single file

I am using the Python gzip module for 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 will see a folder hierarchy corresponding to the path that I wrote gz, and my content is nested in several folders in depth, for example / home / joe in the above example, or C: β†’ Documents and settings β†’ etc. On Windows

How can I get a single file that I clamp to only be in the root directory of the gz file?

+4
source share
4 answers

It looks like you 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 = realf) f.write(content) f.close() real_f.close() 

It seems that open does not allow fileobj to be specified separately from the file name.

+10
source

You should use gzip.GzipFile and put fileobj . If you do, you can specify an arbitrary file name for the gz file header.

+2
source

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

0
source

If you set the current working directory to your output folder, you can call gzip.open ("file.txt.gz") and the gz file will be created without a 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) 
0
source

All Articles