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>It might be easier not to check, line by line and word by word, instead simply check for the word with <code>if (word) in</code>:</p>

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

# Searching for a keyword Name and returning the name if found
def scanName(file):
    name = 'larceny'
    with open(file, 'r') as file1:
        lines = file1.read()
        if name in lines.lower():
            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"):
        if scanName(file):
            print( file )
</code></pre>

<p>Here the entire contents of the file are read in as the variable <code>lines</code>, we check for the searched for word, returning the name of the file, although we could just return <code>True</code>.<br>
If the function returns a result, we print the name of the file.</p>

python python-2.7