The user is looking for a Python program to compress and decompress files using the gzip module. I need to be concise yet detailed, likely providing sample code along with an explanation. I could create two functions for compressing and decompressing files or a small CLI script with argparse.
I plan to handle binary read/write operations correctly, include the necessary .gz extension logic, and implement error handling. I'll provide instructions for running the script as well. Let's get coding without adding any emojis! Here’s a simple Python script that can compress and decompress files using gzip. It works from the command line.
python
#!/usr/bin/env python3
import gzip
import argparse
import os
CHUNK_SIZE = 1024 * 1024 # 1 MB chunks
def compress_file(input_path: str, output_path: str) -> None:
"""Compress a file using gzip."""
with open(input_path, "rb") as f_in, gzip.open(output_path, "wb") as f_out:
while True:
chunk = f_in.read(CHUNK_SIZE)
if not chunk:
break
f_out.write(chunk)
def decompress_file(input_path: str, output_path: str) -> None:
"""Decompress a gzip file."""
with gzip.open(input_path, "rb") as f_in, open(output_path, "wb") as f_out:
while True:
chunk = f_in.read(CHUNK_SIZE)
if not chunk:
break
f_out.write(chunk)
def main():
parser = argparse.ArgumentParser(
description="Compress and decompress files using gzip."
)
subparsers = parser.add_subparsers(dest="command", required=True)
# Compress subcommand
compress_parser = subparsers.add_parser("compress", help="Compress a file")
compress_parser.add_argument("input", help="Input file path")
compress_parser.add_argument(
"output",
nargs="?",
help="Output file path (default: input + '.gz')",
)
# Decompress subcommand
decompress_parser = subparsers.add_parser("decompress", help="Decompress a file")
decompress_parser.add_argument("input", help="Input .gz file path")
decompress_parser.add_argument(
"output",
nargs="?",
help="Output file path (default: input without trailing .gz)",
)
args = parser.parse_args()
if args.command == "compress":
input_path = args.input
output_path = args.output or (input_path + ".gz")
if not os.path.isfile(input_path):
raise FileNotFoundError(f"Input file not found: {input_path}")
compress_file(input_path, output_path)
print(f"Compressed '{input_path}' -> '{output_path}'")
elif args.command == "decompress":
input_path = args.input
if args.output:
output_path = args.output
else:
output_path = (
input_path[:-3] if input_path.endswith(".gz") else input_path + ".out"
)
if not os.path.isfile(input_path):
raise FileNotFoundError(f"Input file not found: {input_path}")
decompress_file(input_path, output_path)
print(f"Decompressed '{input_path}' -> '{output_path}'")
if __name__ == "__main__":
main()
Usage examples (from a terminal):
bash
# Compress
python gzip_tool.py compress myfile.txt
# creates myfile.txt.gz
# Compress with explicit output name
python gzip_tool.py compress myfile.txt archive.gz
# Decompress
python gzip_tool.py decompress myfile.txt.gz
# creates myfile.txt
# Decompress with explicit output name
python gzip_tool.py decompress archive.gz restored.txt
If you’d prefer a version without command-line parsing (just functions to call from another script), I can provide that too.