|
| 1 | +import zlib |
| 2 | +import argparse |
| 3 | +import sys |
| 4 | +import os |
| 5 | + |
| 6 | +def compress_file(input_path, output_path, remove_input=False): |
| 7 | + """Compress a file using zlib compression.""" |
| 8 | + try: |
| 9 | + # Read input file in binary mode |
| 10 | + with open(input_path, 'rb') as input_file: |
| 11 | + data = input_file.read() |
| 12 | + |
| 13 | + # Compress the data |
| 14 | + compressed_data = zlib.compress(data) |
| 15 | + |
| 16 | + # Write compressed data to output file |
| 17 | + with open(output_path, 'wb') as output_file: |
| 18 | + output_file.write(compressed_data) |
| 19 | + |
| 20 | + # Print compression statistics |
| 21 | + original_size = len(data) |
| 22 | + compressed_size = len(compressed_data) |
| 23 | + compression_ratio = (1 - compressed_size / original_size) * 100 |
| 24 | + |
| 25 | + print(f"Compression complete!") |
| 26 | + print(f"Original size: {original_size} bytes") |
| 27 | + print(f"Compressed size: {compressed_size} bytes") |
| 28 | + print(f"Compression ratio: {compression_ratio:.2f}%") |
| 29 | + |
| 30 | + # Remove input file if requested |
| 31 | + if remove_input: |
| 32 | + os.remove(input_path) |
| 33 | + print(f"Input file '{input_path}' deleted.") |
| 34 | + |
| 35 | + except FileNotFoundError: |
| 36 | + print(f"Error: Input file '{input_path}' not found.", file=sys.stderr) |
| 37 | + sys.exit(1) |
| 38 | + except PermissionError: |
| 39 | + print(f"Error: Permission denied accessing files.", file=sys.stderr) |
| 40 | + sys.exit(1) |
| 41 | + except Exception as e: |
| 42 | + print(f"Error: {e}", file=sys.stderr) |
| 43 | + sys.exit(1) |
| 44 | + |
| 45 | +def main(): |
| 46 | + parser = argparse.ArgumentParser(description="Compress a file using zlib compression") |
| 47 | + parser.add_argument("input_file", help="Path to the input file to compress") |
| 48 | + parser.add_argument("output_file", nargs='?', help="Path to the output compressed file (default: input_file + '.z')") |
| 49 | + parser.add_argument("--rm", action="store_true", help="Remove input file after successful compression") |
| 50 | + |
| 51 | + args = parser.parse_args() |
| 52 | + |
| 53 | + # Check if input file exists |
| 54 | + if not os.path.exists(args.input_file): |
| 55 | + print(f"Error: Input file '{args.input_file}' does not exist.", file=sys.stderr) |
| 56 | + sys.exit(1) |
| 57 | + |
| 58 | + # Generate output filename if not provided |
| 59 | + output_file = args.output_file if args.output_file else args.input_file + '.z' |
| 60 | + |
| 61 | + compress_file(args.input_file, output_file, args.rm) |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + main() |
0 commit comments