Python gzip folder structure when zipping single file

前端 未结 4 1612

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 he         


        
相关标签:
4条回答
  • 2021-01-13 17:11

    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.

    0 讨论(0)
  • 2021-01-13 17:14

    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.

    0 讨论(0)
  • 2021-01-13 17:18

    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)
    
    0 讨论(0)
  • 2021-01-13 17:35

    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.

    0 讨论(0)
提交回复
热议问题