gzip a file in Python

后端 未结 7 2053
悲&欢浪女
悲&欢浪女 2020-12-28 12:47

I want to gzip a file in Python. I am trying to use the subprocss.check_call(), but it keeps failing with the error \'OSError: [Errno 2] No such file or directory\'. Is ther

7条回答
  •  有刺的猬
    2020-12-28 12:51

    From the docs for Python3

    Gzip an existing file

    import gzip
    import shutil
    with open('file.txt', 'rb') as f_in:
        with gzip.open('file.txt.gz', 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
    
    # or because I hate nested with statements
    
    import gzip
    import shutil
    from contextlib import ExitStack
    with ExitStack() as stack:
        f_in = stack.enter_context(open('file.txt', 'rb'))
        f_out = stack.enter_context(gzip.open('file.txt.gz', 'wb'))
        shutil.copyfileobj(f_in, f_out)
    

    Create a new gzip file:

    import gzip
    content = b"Lots of content here"
    with gzip.open("file.txt.gz", "wb") as f:
        f.write(content)
    

    Note the fact that content is turned into bytes

    Another method for if you aren't creating content as a string/byte literal like the above example would be

    import gzip
    # get content as a string from somewhere else in the code
    with gzip.open("file.txt.gz", "wb") as f:
        f.write(content.encode("utf-8"))
    

    See this SO question for a discussion of other encoding methods.

提交回复
热议问题