Open the source file using gzip.open in binary read mode ('rb').
Open the destination file in binary write mode ('wb').
Read from source, write to destination.
Code snippet:
python
with gzip.open(src, 'rb') as f_in:
with open(dest, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
Refining the Code Structure:
I need to import gzip and shutil (for efficient copying).
I should create a main block to demonstrate usage.
I should create a dummy file to test the compression on, so the user can run the script immediately.
Writing the Solution (Iterative Refinement):
Imports:import gzip, import shutil, import os (for checking file existence/removal).
Compress Function:
python
def compress_file(input_file, output_file=None):
if output_file is None:
output_file = input_file + '.gz'
with open(input_file, 'rb') as f_in:
with gzip.open(output_file, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
return output_file
Decompress Function:
python
def decompress_file(input_file, output_file=None):
if output_file is None:
# Strip .gz extension
if input_file.endswith('.gz'):
output_file = input_file[:-3]
else:
output_file = input_file + '.decompressed'
with gzip.open(input_file, 'rb') as f_in:
with open(output_file, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
return output_file
Main Execution Block:
Create a text file with some content.
Call compress.
Check file sizes.
Call decompress.
Verify content (optional, but good for demonstration).
Review and Formatting:
The use of shutil.copyfileobj is efficient and pythonic. It handles the chunked reading automatically.
Explain the modes ('rb', 'wb'). Binary mode is crucial for compression to work correctly across platforms.
Add comments explaining the code.
Handle the case where the output filename isn't provided.
Final Output Generation: (This matches the structure of the provided good response).
Import statements.
Function definitions.
Example usage.
Explanation of key parts (rb, wb, shutil).
Self-Correction during drafting:
Initial thought: Just read f_in.read() and write f_out.write(data).
Correction: That loads the whole file into RAM. Bad for big files. Use shutil.copyfileobj.
Initial thought: Just use gzip.open for everything.
Correction: You need standard open for the raw file and gzip.open for the compressed one, swapping them depending on the direction (compress vs decompress).
Final Code Assembly: (Produces the Python script provided in the final answer).
Here is a complete Python program that demonstrates how to compress and decompress files using the built-in gzip module.
This script uses shutil.copyfileobj, which is the most memory-efficient way to handle large files, as it reads and writes in chunks rather than loading the entire file into RAM.
Python Script
python
import gzip
import shutil
import os
def compress_file(input_file, output_file=None):
"""
Compresses a file using gzip.
:param input_file: Path to the file to compress.
:param output_file: Path for the output .gz file. If None, appends .gz to input.
"""
if not os.path.exists(input_file):
print(f"Error: The file '{input_file}' does not exist.")
return
if output_file is None:
output_file = input_file + ".gz"
try:
with open(input_file, 'rb') as f_in:
with gzip.open(output_file, 'wb') as f_out:
# copyfileobj efficiently copies data in chunks
shutil.copyfileobj(f_in, f_out)
print(f"Success: Compressed '{input_file}' to '{output_file}'")
except Exception as e:
print(f"Error during compression: {e}")
def decompress_file(input_file, output_file=None):
"""
Decompresses a gzip file.
:param input_file: Path to the .gz file.
:param output_file: Path for the decompressed file. If None, removes .gz extension.
"""
if not os.path.exists(input_file):
print(f"Error: The file '{input_file}' does not exist.")
return
if output_file is None:
# Remove .gz extension for output filename
if input_file.endswith('.gz'):
output_file = input_file[:-3]
else:
print("Error: Input file does not have .gz extension and no output filename provided.")
return
try:
with gzip.open(input_file, 'rb') as f_in:
with open(output_file, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
print(f"Success: Decompressed '{input_file}' to '{output_file}'")
except Exception as e:
print(f"Error during decompression: {e}")
# --- Example Usage ---
if __name__ == "__main__":
# 1. Create a dummy file to test with
dummy_name = "demo_file.txt"
with open(dummy_name, "w") as f:
f.write("This is a test string to demonstrate gzip compression in Python.\n" * 100)
print("--- Starting Compression Test ---")
# 2. Compress the file
compress_file(dummy_name)
# 3. Delete the original file to prove decompression works
os.remove(dummy_name)
print("\n--- Starting Decompression Test ---")
# 4. Decompress the file
decompress_file(dummy_name + ".gz")
# 5. Clean up
if os.path.exists(dummy_name + ".gz"):
os.remove(dummy_name + ".gz")
if os.path.exists(dummy_name):
os.remove(dummy_name)
Key Details
Binary Mode ('rb', 'wb'):
When working with compression, you must handle files in binary mode.
open(..., 'rb'): Reads the source file as raw bytes.
gzip.open(..., 'wb'): Writes the compressed bytes to the new file.
shutil.copyfileobj:
Instead of reading the whole file using f_in.read(), we use shutil.copyfileobj(f_in, f_out). This reads the file in small chunks (buffers) and writes them immediately. This allows you to compress files that are larger than your computer's available RAM (e.g., compressing a 10GB log file).
Compression Level:
By default, gzip uses a compression level of 9 (the maximum). If you want faster compression (but a slightly larger file), you can add compresslevel=1 to the gzip.open call: