Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

python - Change newline character .readline() seeks

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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='
'):
    buf = bytearray(), 
    while True:
        c = self.read(1)
        if c == '': return
        buf += c
        if c == delim: 
            yield str(buf)
            buf = bytearray()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...