Compress and restore exact CSV bytes with Python
Creates gzip output and a byte-identical restored.csv without parsing the CSV.
Before you start
- Python 3.10 or later. Run in a working folder with a backup of your source; output files may be replaced unless opened in exclusive mode.
- Place input.csv in that folder. Examples use UTF-8, a comma delimiter and a header row. Column-specific recipes use id,label,amount,status,note; adapt names to your file.
python3 - <<'PY'
import gzip
import shutil
with open("input.csv", "rb") as source, gzip.open("input.csv.gz", "wb") as target:
shutil.copyfileobj(source, target)
with gzip.open("input.csv.gz", "rb") as source, open("restored.csv", "wb") as target:
shutil.copyfileobj(source, target)
with open("input.csv", "rb") as original, open("restored.csv", "rb") as restored:
assert original.read() == restored.read()
print("Created input.csv.gz and verified restored.csv matches the original bytes")
PYLimits and output
- CSV has no stored type schema. Python keeps fields as strings until an example explicitly converts a value. These recipes do not add spreadsheet formula protection; import sensitive-looking strings as text in spreadsheets.
- Compression is streamed, but the final equality check loads both files into memory. Small or already compressed content may not get smaller.
Documentation: Python CSV reader and writer; Python gzip