Find a string that is not identical with Python
<p>So.. here's what i'm trying to do..
For each line in the datafile, check if the other file contains this string.</p>

<p>I tried some stuff from other posts, but non of them were any good.</p>

<p>The code below says it didnt find any of the string it was looking for, even while they were present somewhere in the file.</p>

<pre><code>def search():
    file1= open('/home/example/file1.txt', 'r')
    datafile= open('/home/user/datafile.txt', 'r')

    for line in datafile:
        if line in file1:
            print '%s found' % line
        else:
            print '%s not found' % line
</code></pre>

<p><strong>EDIT:</strong>
I want it to find a match if the line is not identical.</p>

<p>Example: It should find <strong>hello</strong> in the document if it's written as <strong>hello123</strong></p>

<p>You can read the file into a <code>set</code> and then check for inclusion in the second file. <code>set</code>'s are typically faster at checking inclusion that lists.</p>

<pre><code>def search():
    file1 = set(open('/home/example/file1.txt'))
    datafile= open('/home/user/datafile.txt', 'r')

    for line in datafile:
        if line in file1:
            print '%s found' % line
        else:
            print '%s not found' % line
</code></pre>

<p>You could also use set operations to extract, for instance, all lines not in the first file:</p>

<pre><code>set(open('/home/user/datafile.txt', 'r')) - set(open('/home/example/file1.txt'))
</code></pre>

python