【问题标题】:Change newline character .readline() seeks更改换行符 .readline() 寻求
【发布时间】:2011-06-08 19:58:10
【问题描述】:

是否可以更改.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"
>>>

【问题讨论】:

    标签: python input readline


    【解决方案1】:

    没有。

    考虑使用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()
    

    【讨论】:

    • 我用我所想的代码示例进行了编辑;继承 file 对象。
    • 如目前所写,如果文件不以delim 字符结尾,则yield 不会出现任何尾随字符。也许使用if c == '': return str(buf) 可能会更好。
    猜你喜欢
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多