# Zipping and unzipping a string using the zlib module # A very large string cocould be zipped and saved to a file speeding up file writing time # And later reloaded and unzipped by another program speeding up reading of the file # Tested with Python24 vegaseat 15aug2005 Import zlib Str1 = "Dallas Cowboys football practice at Valley Ranch was delayed on Wednesday For nearly two hours. One of the players, while on his way to the locker Room happened to look down and notice a suspicious looking, unknown white Powdery substance on the practice field. The coaching staff immediately susponded practice while the FBI was Called in to investigate. After a complete field analysis, the FBI Determined that the white substance unknown to the players was the goal Line. Practice was resumed when FBI Special Agents decided that the team wocould not Be likely to encounter the substance again. """ Print '-' * 70 #70 dashes for the fun of it Print str1 Print '-' * 70 Crc_check1 = zlib. crc32 (str1) Print "crc before zip =", crc_check1 Print "Length of original str1 =", len (str1) # Zip compress the string Zstr1 = zlib. compress (str1) Print "Length of zipped str1 =", len (zstr1) Filename = 'Dallas. zap' # Write the zipped string to a file Fout = open (filename, 'w ') Try: Print> fout, zstr1 Handle t IOError: Print "Failed to open file ..." Else: Print "done writing", filename Fout. close () # Read the zip file back Fin = open (filename, 'R ') Try: Zstr2 = fin. read () Handle t IOError: Print "Failed to open file ..." Else: Print "done reading", filename Fin. close () # Unzip the zipped string from the file Str2 = zlib. decompress (zstr2) Print '-' * 70 Print str2 Print '-' * 70 Crc_check2 = zlib. crc32 (str2) Print "crc after unzip =", crc_check2, "(check sums shocould match )" |