faqts : Computers : Programming : Languages : Python : Snippets : Stream Manipulation : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 3 people (67%) answered Yes
Recently 1 of 1 people (100%) answered Yes

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
"""