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 if you 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.
archive.tar.gz
from a directory/dir/path
, you could useshutil.make_archive('archive', 'gztar', '/dir/path')
– Chat