#逐行統計關鍵字行數,並將關鍵字所在行存放在新的文件中 keyword = "INFO" b = open("C:\\Users\\xxx\\Documents\\new.txt", "w",encoding='UTF-8') a = open("C:\\Users\\xxx\\Documents\\log-count-data.txt", "r",encoding='UTF-8') #注意此處的轉義字符 count=len(open(r"C:\\Users\\xxx\\Documents\\log-count-data.txt",'r',encoding='UTF-8').readlines())#使用len+readlines讀取行數 #print(count) i = 0 while i < count:#使用循環遍歷所有行,逐行判斷,只要有關鍵字,就存到新文件 line = a.readline() if keyword in line:#此處注意代碼縮進 print(line) b.write(line + '\n')#注意每寫一行都需要換行 i+=1 row=len(open(r"C:\\Users\\xxx\\Documents\\new.txt",'r',encoding='UTF-8').readlines())#統計新文件有多少行 a.close() b.close() print("一共有%d行" %count) print("含有%s關鍵字的有%d行" %(keyword,row))#此處使用格式化方法 百分號+括號
此篇主要涉及文件的讀寫技巧,逐行匹配,總體邏輯是比較簡單的,主要是編碼過程中,需要對縮進、格式化和其他一些細節進行思考。
log-count-data.txt數據文件來自阿里雲批量計算的示例 https://help.aliyun.com/document_detail/28010.html?spm=a2c4g.11186623.6.553.MW98di