Skip to content

Instantly share code, notes, and snippets.

@glassdfir
Created January 21, 2015 20:54
Show Gist options
  • Save glassdfir/d586620cff6e18b37597 to your computer and use it in GitHub Desktop.
Save glassdfir/d586620cff6e18b37597 to your computer and use it in GitHub Desktop.
import zlib,sys
def deflate( data ):
zlibbed_data = zlib.compress( data )
#remove byte 0-1(header) and the last four(checksum)
compressed_data = zlibbed_data[2:-4]
return compressed_data
def inflate(compressed_data2):
# -15 for the window buffer will make it ignore headers/footers
zlibbed_data2 = zlib.decompress(compressed_data2, -15)
return zlibbed_data2
##################################################
#1. Create test file in current working directory#
##################################################
str = "Zip Files Rule! " * 15
with open('uncompressed.txt', 'w') as make_file:
make_file.write(str)
make_file.closed
#################################
#2. Read in file we just created#
#################################
with open("uncompressed.txt", "r+b") as uncompressed_file:
uncompressed_file_data = uncompressed_file.read()
uncompressed_file.closed
##############################################################
#3. Make a file that contains JUST deflated (compressed) data#
#In a real world scenario, this could be an example of a zip #
#file that has a bad header or footer BUT the raw data is #
#still intact. #
##############################################################
with open("compresseddata.bin", "w") as compressed_file_data:
compressed_file_data.write(deflate(uncompressed_file_data))
compressed_file_data.closed
################################################################
#4. Read file with just compressed data, decompress it and save#
#it back to disk #
################################################################
with open("compresseddata.bin", "r+b") as read_compressed_file:
file_data_to_be_uncompressed = read_compressed_file.read()
read_compressed_file.closed
with open("inflated.txt", "w") as inflated_file:
inflated_file.write(inflate(file_data_to_be_uncompressed))
inflated_file.closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment