更改换行符.readline()寻求

tMC*_*tMC 6 python input readline

是否可以.readline()在读取行时更改方法查找的换行符?我可能需要从文件对象中读取一个流,该文件对象将以换行符之外的其他内容分隔,并且一次获取一个块可能很方便. 如果我可以使用,那么file对象没有readuntil我不必创建的对象readline

编辑:


我还没有在管道上试过它stdin; 但这似乎有效.

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)
Run Code Online (Sandbox Code Playgroud)

用法:

>>> 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"
>>>
Run Code Online (Sandbox Code Playgroud)

paj*_*ton 6

没有.

考虑创建一个使用file.read()和生成由给定字符分隔的块的生成器.

编辑:

您提供的样本应该可以正常工作.我更喜欢使用发电机:

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()
Run Code Online (Sandbox Code Playgroud)