Search txt file for varying keyword - then assign to variable
<p>I need to search a txt file for keywords in format "i-0xxxyyyzzzz" - where xyz are varying alphanumeric characters.
I would like to then assign each match assigned. Currently I can get as far as:</p>

<pre><code>  f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "i-0" in line:
        for l in searchlines[i:i+1]: print l,
        print
</code></pre>

<p>However this prints the whole line, and not just the keyword.</p>

<p>I suggest using regular expressions:</p>

<pre><code>import re

token_regex = re.compile('i\-0[0-9a-z]*')
for line in open('file.txt'): // Note: 'r' is the default
   // You might find the token several times in the line
   matches = token_regex.findall(line)
   if matches:
     print '\n'.join(matches)
</code></pre>

<p>I'm not clear what you want to do with the matches. My example would print print them one per line. Also, could you have tokens that span two lines?</p>

python file search keyword