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
From the docs for Python3
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)
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.