我正在編寫一個Python程序來讀取文本文件並提取一些信息。我試圖找到三個項目,一個實數和兩個列表。該腳本將文本文件的行存儲爲列表inLines
。在閱讀腳本時,腳本使用for curLine in inLines:
,然後在所有行中搜索特定的鍵。找到搜索關鍵字後,我想將inLines
的剩餘部分傳遞給一個函數,再讀幾行,然後返回到函數停止行的主腳本。將部分列表傳遞給Python函數
這裏是什麼,我希望發生的事情(給出意見代碼指令)
line of text that doesn't matter #Read by main, nothing interesting happens
line of text that doesn't matter #Read by main, nothing interesting happens
search key A #Read by main, all following lines passed to function A
line that matters #Read by function A, stores in object
line that matters #Read by function A, stores in object
line that matters #Read by function A, stores in object
search key B #Read by function A, return to main, all following lines passed to function B
line that matters #Read by function B, stores in object
search key C #Read by function B, return to main, all following lines passed to function C
line that matters #Red by function C, stores in object
所以每個搜索鍵告訴其功能是在程序(和不同的密鑰可以以任意順序一個小圖)當腳本找到該鍵時,它將所有更多的行傳遞給正確的函數,並且每當函數找到一個搜索鍵時,它就會中斷,並將所有其他行傳回主(然後將相同的行傳遞給相應的函數)
對不起,這本書的一個問題,我剛剛學習了多年FORTRAN之後的Python,所以如果任何人都能想到更好的方法來解決這個問題,我願意提供建議。在此先感謝
你可以傳遞一個文件句柄到一個函數,然後在該函數中繼續'for l in inf'(雖然我現在不能寫一個完整的答案) – 2013-02-18 20:54:52