我正在循環瀏覽一個文件,如果我找到了某些內容,想在將控制權返回給主循環之前預讀幾行代碼。但是,我想在我停止展望的時候返回控制權。如何在使用Python循環時讀取文件中的文件?
示例代碼:
for line in file:
line = line.strip()
llist = line.split()
if llist[0] == 'NUMS':
# some loop to read ahead and print nums on their own line
# until it finds END, then return control to the main for
# loop at the point where it stopped looking ahead.
樣品輸入:
NUMS
1
2
3
4
5
END
SOME
MORE
STUFF
NUMS
6
7
8
9
0
END
所需的輸出:
1 2 3 4 5
6 7 8 9 0
我是相當新的Python的,所以如果有一個更好的辦法做到除了使用循環展望外,我很高興看到它。
因此,文件中的'for line:'開始在外部的一個斷開的線上?我原以爲它會從文件的開頭開始。 – astay13
@astay:這與內部/外部無關。這段代碼中只有一個迭代器。 ''只是循環獲取下一個東西,直到迭代器引發StopIteration。你可以跳出循環並開始另一個循環,繼續獲得下一個循環。 –
@John and Petr,感謝您幫助我更好地理解文件/迭代器!我選擇這個解決方案,因爲我的代碼需要大約500行預測。 – astay13