Python matching lines of a file with a list of strings
<p>High-level requirement is that I need an equivalent of "grep -f match_str_file search_file".</p>

<p>I have a list of strings which I need to find in a given text file.
The string may occur anywhere in any line of file.</p>

<p>What would be an efficient way to achieve this?</p>

<pre><code>matchstr = ['string1', 
'string2', 
'string3',
...
'string1000']

with open('some_text_file') as file:
    for line in file:
        if &lt;any matchstr&gt; in line:
            print( 'Found a match!', matchstr[x])
</code></pre>

<p>Try this:</p>

<pre><code>matchstr = ['string1', 
'string2', 
'string3',
...
'string1000']

matches = []
def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1
while 1:
    lines = file.readlines(file_len("fjiop.txt"))
    if not lines:
        break
    for line in lines:
        matches.append([match, line] for match in matchstr if match in line)
</code></pre>

<p>Note that this will create generators inside generators so to loop through it use:</p>

<pre><code>for i in matches:
    for j in i:
        #do stuff
</code></pre>

python python-3.x string-matching