Fred Bongers
Fred Bongers

Reputation: 267

Search for word in text file in Python

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

Answers (3)

AdrienW
AdrienW

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 :

  1. Replace term = 'model' by term = 'model,' and this will only show the line you want.

  2. 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

  • You could use startswith('somechars') to check for some characters at the beginning of a string
  • You need to assign the result of strip() and split(\n) in your variable, otherwise nothing happens.
  • It's also better to use the keyword with instead of opening/closing files
  • In general, I think you'd be better served with regular expressions for that type of thing you're doing. However, as pointed out by Nander Speerstra's comment, this could be dangerous.

Upvotes: 1

Ohad Eytan
Ohad Eytan

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

milos.ai
milos.ai

Reputation: 3930

Just replace the line:

if term in line:

with line :

if line.startswith('model,'):

Upvotes: 3

Related Questions