Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created February 29, 2012 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdwhatcott/1943947 to your computer and use it in GitHub Desktop.
Save mdwhatcott/1943947 to your computer and use it in GitHub Desktop.
Context-managed, iterable, in-memory file
from StringIO import StringIO
class MemoryFile(StringIO):
"""
This abstraction provides context management and line-iteration over the
built-in StringIO class, making it more fully behave like a file object.
Unfortunately, iteration is not (yet?) memory-efficient for large files.
"""
def __init__(self, text=''):
StringIO.__init__(self, text)
self.lines = None
self.index = 0
def __iter__(self):
self.lines = self.getvalue().split('\n')
return self
def next(self):
index = self.index
self.index += 1
try:
return self.lines[index]
except IndexError:
raise StopIteration
def __enter__(self):
return self
def __exit__(self, *args):
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment