2011-06-02 60 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