Python 读取 next()
在Python中,next()
这个函数不工作了。那有没有其他方法可以读取下一行呢?下面是一个示例:
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 '。
6 个回答
4
lines = f.readlines()
这段话的意思是,它会把文件f里的所有行都读出来。所以,文件f里就没有更多的行可以读了。如果你想一行一行地读文件,可以使用readline()这个方法。
39
当你执行 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
25
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