2011-06-02 46 views
11

python 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' 指

Brgds,

kNish

回答

13

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 
23

当你这样做: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 
2
lines = f.readlines() 

读取文件F的所有行。所以有意义的是,在文件f中没有更多行要读取。 如果要逐行读取文件,请使用readline()。

0

你并不需要读取下一行,您是通过迭代线。 是一个列表(一个数组),并且行迭代它。每当你完成一个你移动到下一行。如果你想跳到下一行,只需要继续退出当前循环。

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

lines = f.readlines() # get all lines as a list (array) 

# Iterate over each line, printing each line and then move to the next 
for line in lines: 
    print line 

f.close() 
+0

并作为维塔说你已经用f.readlines读完了整个文件。您没有迭代该文件,整个文件已被读入内存。 – 2011-06-02 10:16:53

1

你的算法的一个小的变化:从itertools recipes

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

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

f.close() 

然而,使用pairwise功能:

def pairwise(iterable): 
    "s -> (s0,s1), (s1,s2), (s2, s3), ..." 
    a, b = itertools.tee(iterable) 
    next(b, None) 
    return itertools.izip(a, b) 

你可以改变你的循环为:

for line, next_line in pairwise(f): # iterate over the file directly 
    print line 
    if line.startswith("anim "): 
     print 'next() ' 
     print ' ne ', next_line, '\n' 
     break