Searching and reading from file with python
<p>I am trying to search for a specific words in a file and print it.</p>

<p>Here is my code:</p>

<pre><code>import os # os directory library

# Searching for a keyword Name and returning the name if found
def scanName(file):
    name = 'Fake'
    with open('file.txt', 'r') as file1:
        for line in file1:
            for word in line.split():
                temp = word
                if temp.lower() == 'name'.lower():
                    name = word[word.index("name") + 1]
    return name



# To find all files ending with txt in a folder
for file in os.listdir("C:\Users\Vadim\Desktop\Python"):
   if file.endswith(".txt"):
       print scanName( file )
</code></pre>

<p>Now the function return the name as fake although a do have names in my txt files.</p>

<p>Two txt files with string "name: some name"</p>

<p>How do i fix it?</p>

<p>Thanks!</p>

<p>Replace <code>'name'.lower()</code> with <code>name.lower()</code>, because you are now checking with the <em>string</em> <code>name</code>, instead of the <em>variable</em> <code>name</code>.</p>

python python-2.7