Created
February 29, 2012 19:51
-
-
Save mdwhatcott/1943947 to your computer and use it in GitHub Desktop.
Context-managed, iterable, in-memory file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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