更改.readline()的换行符

6 投票
1 回答
3484 浏览
提问于 2025-04-16 19:12

可以改变 .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)

用法:

>>> 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 个回答

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()

撰写回答