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()
Run Code Online (Sandbox Code Playgroud)
在文件上运行此操作不会显示"ne".
mou*_*uad 29
执行此操作时:f.readlines()您已经读取了所有文件,因此f.tell()会显示您位于文件末尾,这样做f.next()会导致StopIteration错误.
您想要做的事情的替代方案是:
filne = "D:/testtube/testdkanimfilternode.txt"
with open(filne, 'r+') as f:
for line in f:
if line.startswith("anim "):
print f.next()
# Or use next(f, '') to return <empty string> instead of raising a
# StopIteration if the last line is also a match.
break
Run Code Online (Sandbox Code Playgroud)
vit*_*aut 17
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
Run Code Online (Sandbox Code Playgroud)