[英]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.