我有这个文本文件:
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
我该怎么做?
答案 0 :(得分:3)
只需更换一行:
if term in line:
行:
if line.startswith('model,'):
答案 1 :(得分:1)
这取决于您的文件包含的内容。您的示例非常简单,但我看到一些不会过多更改代码的直接解决方案:
将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
代替打开/关闭文件也更好答案 2 :(得分:1)
您可以按,
拆分该行并检查第一个字段:
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()