更改换行符.readline()寻求 [英] Change newline character .readline() seeks

查看:108
本文介绍了更改换行符.readline()寻求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

除了stdin之外,我还没有在其他管道上尝试过它;但这似乎可行.

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)

用法:

>>> 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"
>>>

推荐答案

否.

考虑使用file.read()创建生成器并产生以给定字符分隔的块.

Consider creating a generator using file.read() and yielding chunks delimited by given character.

您提供的示例应该可以正常工作.我更愿意使用发电机:

The sample you provided should work just fine. I would prefer to use a generator though:

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

这篇关于更改换行符.readline()寻求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆