Find one file out of many containing a desired string in Python
<p>I have a string like 'apples'. I want to find this string, and I know that it exists in one out of hundreds of files. e.g.</p>

<pre><code>file1
file2
file3
file4
file5
file6
...
file200
</code></pre>

<p>All of these files are in the same directory. What is the best way to find which file contains this string using python, knowing that exactly one file contains it.</p>

<p>I have come up with this:</p>

<pre><code>for file in os.listdir(directory):
    f = open(file)
    for line in f:
        if 'apple' in f:
            print "FOUND"
    f.close()
</code></pre>

<p>and this:</p>

<pre><code>grep = subprocess.Popen(['grep','-m1','apple',directory+'/file*'],stdout=subprocess.PIPE)
found = grep.communicate()[0]
print found
</code></pre>
