更改换行符 .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)
用法:
>>> 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"
>>>
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
EDIT:
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)
usage:
>>> 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"
>>>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
否。
考虑使用 file.read() 创建一个生成器并生成由给定字符分隔的块。
编辑:
您提供的示例应该可以正常工作。不过我更喜欢使用发电机:
No.
Consider creating a generator using
file.read()
and yielding chunks delimited by given character.Edit:
The sample you provided should work just fine. I would prefer to use a generator though: