brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -m gzip compresses a file and keeps the original

Python
~/tips/tip-python-m-gzip-keep-original

python3 -m gzip --best access.log # writes access.log.gz, keeps access.log

Compress or decompress a gzip file with Python when you want the source kept.

The gzip command replaces your file with the compressed one. Python’s gzip module has a small command line too, and it leaves the input file alone.

python3 -m gzip --best access.log      # writes access.log.gz, keeps access.log
python3 -m gzip -d access.log.gz       # writes access.log again

That keeps the original, which is what I want when I’m about to send a log to someone or attach it to an issue, and still need the uncompressed file for myself. --best and --fast pick the compression level, the same trade off as with the real gzip.

It’s also a fallback in minimal containers that have Python but no gzip binary, which happens more often than you’d think with slim images.

Watch out with -d, though. It writes the output file without asking, so if access.log already exists it gets overwritten. GNU gzip would ask first or refuse. And there’s no -c to write to standard output or -r for folders: it takes file names and that’s it. For anything beyond one file, the system gzip -k (keep) does the same job with more options, so I’d only use the Python one when gzip isn’t there.

Further reading: gzip command line interface

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link