Python阅读next()

发布于 2021-01-29 15:13:35

next()在python中不起作用。在Python中阅读下一行的替代方法是什么?这是一个示例:

filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')

while 1:
    lines = f.readlines()
    if not lines:
        break
    for line in lines:
        print line
        if (line[:5] == "anim "):
            print 'next() '
            ne = f.next()
            print ' ne ',ne,'\n'
            break

f.close()

在文件上运行此命令不会显示“ ne”。

关注者
0
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    next()在您的情况下不起作用,因为您首先调用的readlines()方法基本上将文件迭代器设置为指向文件末尾。

    由于您仍在阅读所有行,因此可以使用索引来参考下一行:

    filne = "in"
    with open(filne, 'r+') as f:
        lines = f.readlines()
        for i in range(0, len(lines)):
            line = lines[i]
            print line
            if line[:5] == "anim ":
                ne = lines[i + 1] # you may want to check that i < len(lines)
                print ' ne ',ne,'\n'
                break
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看