Change newline character .readline() seeks

2019-01-26 12:53发布

问题:

Is it possible to change the newline character the .readline() method looks for while reading lines? I might have the need to read a stream from a file object that will be delimited in something other than newlines and it could be handy to get a chunk at a time. file objects don't have a readuntil which I wouldn't have to create if I can use readline

EDIT:


I haven't yet tried it on a pipe other than stdin; but this seems to work.

class cfile(file):
    def __init__(self, *args):
        file.__init__(self, *args)

    def readuntil(self, char):
        buf = bytearray()
        while True:
            rchar = self.read(1)
            buf += rchar
            if rchar == char:
                return str(buf)

usage:

>>> import test
>>> tfile = test.cfile('/proc/self/fd/0', 'r')
>>> tfile.readuntil('0')
this line has no char zero
this one doesn't either,
this one does though, 0
"this line has no char zero\nthis one doesn't either,\nthis one does though, 0"
>>>

回答1:

No.

Consider creating a generator using file.read() and yielding chunks delimited by given character.

Edit:

The sample you provided should work just fine. I would prefer to use a generator though:

def chunks(file, delim='\n'):
    buf = bytearray(), 
    while True:
        c = self.read(1)
        if c == '': return
        buf += c
        if c == delim: 
            yield str(buf)
            buf = bytearray()