3:46:26 am on 1/8/09
Menu
» Home
» About Scott
» Old Stuff
» Archive
» Contact

Writings
» MD Labels
» Streamrip
» AIM Thoughts
» WindowsXP?
» Partitioning
» CD/DVD Repair
» Monitor Info
» CRT Deflection
» Venomcrack
» Flash Thing
» Heart/Brain
» Diabetes
» Triops

Friends
» Kyle
» Nick
» Louis
» Tom



Archives
» January 2009
» December 2008
» November 2008
» October 2008
» September 2008
» September 2007
» December 2006
» August 2006
» January 2006
» December 2005
» August 2005
» July 2005
» June 2005
» May 2005
» April 2005
» March 2005
» February 2005
» January 2005
» December 2004
» November 2004
» October 2004
» September 2004
» August 2004
» July 2004
» June 2004
» May 2004
» April 2004
» March 2004
» February 2004
» January 2004
» December 2003
» November 2003
» October 2003
» September 2003
» August 2003
» July 2003
» June 2003
» May 2003
» April 2003
» March 2003
» February 2003
» January 2003
» December 2002
» November 2002
» October 2002
» September 2002
» June 2001
« Run Ubuntu Live CD From a USB Drive
Is Descriptive Eloquence Inherited? »


Compress Strings and Store to Files in Python
223 words

While writing code for my graduate research thesis I came across the need to lightly compress a huge and complex variable (a massive 3D data array) and store it in a text file for later retrieval. I decided to use the zlib compression library because it’s open source and works pretty much on every platform. I ran into a snag for a while though, because whenever I loaded data from a text file it wouldn’t properly decompress. I fixed this problem by adding the “rb” to the open line, forcing python to read the text file as binary data rather than ascii data. Below is my code, written in two functions to save/load compressed string data to/from files in Python.

import zlib

def saveIt(data,fname):
    data=str(data)
    data=zlib.compress(data)
    f=open(fname,'wb')
    f.write(data)
    f.close()
    return

def openIt(fname,evaluate=True):
    f=open(fname,'rb')
    data=f.read()
    f.close()
    data=zlib.decompress(data)
    if evaluate: data=eval(data)
    return data

Oh yeah, don’t forget the evaluate option in the openIt function. If set to True (default), the returned variable will be an evaluated object. For example, “[[1,2],[3,4]]” will be returned as an actual 2D list, not just a string. How convenient is that?



This entry was posted on Monday, November 24th, 2008 at 5:48 pmand is filed under General. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.

Leave a Reply




copyright © 2006 swharden@gmail.com