python - 更改换行符 .readline() 查找

标签 python input readline

是否可以更改 .readline() 方法在读取行时查找的换行符?我可能需要从一个文件对象中读取一个流,该文件对象将以换行符以外的其他方式分隔,并且一次获取一个 block 可能很方便。 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"
>>>

最佳答案

没有。

考虑使用 file.read() 创建生成器并生成由给定字符分隔的 block 。

编辑:

您提供的示例应该可以正常工作。不过我更愿意使用生成器:

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

关于python - 更改换行符 .readline() 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6284468/

相关文章:

python - 打印十六进制值时如何让 Python 使用大写字母?

python - 如何使用python从mongodb获取游标的长度?

javascript - 单击另一个表单输入字段时自动勾选复选框

java - Bufferedreader 不能一次读取整行?

python - 逐行读取文本文件并存储匹配 Python 中特定模式的变量

python - 使用 BeautifulSoup 抓取网站并保持不变的 URL

python - 检查 Python 中的 TensorFlow 版本 - "tf.__version__"与 "tf.VERSION"?

C++ 无法获取 strtok 的用户输入

python - 从输入访问字典内的列表

string - Bash:完全像 Readline 一样拆分字符串