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
this one doesn't either,
this one does though, 0"
>>>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…