简体   繁体   中英

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?

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 :

  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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM