Entry
Special behavior when reading files
Jul 5th, 2000 09:59
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 68, Evan Simpson
"""
Packages: files;text
"""
"""
>In addition, I am planning to add some special behaviour. For example,
>setting sep to '' causes the file to be read in paragraph mode.
Try this:
"""
class ReadSep:
def __init__(self, f, sep):
self.f = f
self.sep = sep
self.bitsleft = ['']
def readSep(self):
bit, bits = '', self.bitsleft
if len(bits)==0:
return ''
from string import split
get = self.f.read
while 1:
bit, self.bitsleft = bit + bits[0], bits[1:]
if len(self.bitsleft)>0:
return bit+self.sep
chunk = get(1024)
if not chunk:
return bit
bits = split(chunk, self.sep)
def readSepFun(f, sep=None):
if sep==None:
return f.readline
return ReadSep().readSep
"""
If you liked, you could combine this with the lazy 'repeat' found in a
recent thread and write:
f = open('file', 'r')
fetch = readSepFun(f, ';')
for part in repeat(fetch):
# process part
"""