1. 程式人生 > 其它 >【Python 基礎】讀取具有特定特徵的行的例子

【Python 基礎】讀取具有特定特徵的行的例子

返回:Python基礎 索引頁

假設我的 程式是要讀取如下型別的檔案:

###
[Action --1]

RDMA support
IPOIB support
RDSOIB support

###<<<

###
[Action --2]

ORA-07445 
pevm_icd_call_common
ORA 7445 [pevm_icd_call_common]
oracle.sysman.oui.patch.PatchException: java.io.FileNotFoundException: 
ContentsXML/oui-patch.xml (Permission denied)

opatch logs

###<<<

我想找出每一個 "###" 之後的第一行,把它們彙集到一個列表裡,
再都打印出來。

程式如下:

mylist = []

myfile = open('AI.txt')
line = myfile.readline()

while line:    
    current_line = line.strip()
    if ( current_line == "###" ) :  # read the next line when encounter ###
        line = myfile.readline()
        current_line 
= line.strip() mylist.append(current_line) line = myfile.readline() # to move to the next line myfile.close() for temp in mylist: print(temp)

執行結果如下:

[Action --1]
[Action --2]

返回:Python基礎 索引頁