Reputation: 267
I have this text file:
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
I need to find the line with the model.
My code:
term = "model"
file = open('file.txt')
for line in file:
line.strip().split('/n')
if term in line:
print line
file.close()
This is the output:
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
I need only this line as output:
model,3,2016-07-30 15:39:59,075
How can I do this?
Upvotes: 1
Views: 23962
Reputation: 3452
It depends on what your file contains. Your example is quite light, but I see a few immediate solutions that don't change your code too much :
Replace term = 'model'
by term = 'model,'
and this will only show the line you want.
Use some additional criteria, like "must not contain 'name'
":
Like this:
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
Additional remarks
startswith('somechars')
to check for some characters at the beginning of a stringstrip()
and split(\n)
in your variable, otherwise nothing happens.with
instead of opening/closing filesUpvotes: 1
Reputation: 8464
You can split the line by ,
and check for the first field:
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()
Upvotes: 1
Reputation: 3930
Just replace the line:
if term in line:
with line :
if line.startswith('model,'):
Upvotes: 3