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?
Just replace the line:
if term in line:
with line :
if line.startswith('model,'):
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 string strip()
and split(\\n)
in your variable, otherwise nothing happens. with
instead of opening/closing files 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.