如何在Python 3中查看文件中的下一个字符?

时间:2016-10-14 22:44:24

标签: python-2.7 python-3.x seek peek

假设我正在构建一个解析器,我想在流中预见。

在Python 2中,我可以写:

def peek():
    next = inputfile.read(1)
    inputfile.seek(-1,1)
    return next

然而,在Python 3中,相对搜索被禁用。

3 个答案:

答案 0 :(得分:1)

这在文本模式下不起作用,但是在二进制模式下起作用:

>>> open('test', 'rb').peek(1)
b'test\n'

答案 1 :(得分:0)

相反,您可以使用inputfile.peek(1)[:1]

答案 2 :(得分:0)

file.read(1)
file.seek(file.tell()-1)
相关问题