[英]Search for word in text file in Python
我有這個文本文件:
MemTotal,5,2016-07-30 12:02:33,781
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
我需要找到與模型一致的線。
我的代碼:
term = "model"
file = open('file.txt')
for line in file:
line.strip().split('/n')
if term in line:
print line
file.close()
這是輸出:
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
我只需要此行作為輸出:
model,3,2016-07-30 15:39:59,075
我怎樣才能做到這一點?
只需替換行:
if term in line:
與線:
if line.startswith('model,'):
這取決於您的文件包含什么。 您的示例很簡單,但是我發現一些即時解決方案不會對您的代碼造成太大影響:
更換term = 'model'
通過term = 'model,'
這將只顯示你想要的行。
使用一些其他條件,例如“不得包含'name'
“ :
像這樣:
term = 'model'
to_avoid = 'name'
with open('file.txt') as f:
for line in file:
line = line.strip().split('/n')
if term in line and to_avoid not in line:
print line
補充說明
startswith('somechars')
來檢查字符串開頭的某些字符 strip()
和split(\\n)
的結果,否則什么也不會發生。 with
關鍵字而不是打開/關閉文件 您可以按來分隔行,
然后檢查第一個字段:
term = "model"
file = open('file.txt')
for line in file:
line = line.strip().split(',') # <---
if term == line[0]: # <--- You can also stay with "if term in line:" if you doesn't care which field the "model" is.
print line
file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.