Kiper
Kiper

Reputation: 339

Searching and reading from file with python

I am trying to search for a specific words in a file and print it.

Here is my 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 )

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

Two txt files with string "name: some name"

How do i fix it?

Thanks!

Upvotes: 0

Views: 108

Answers (2)

Rolf of Saxony
Rolf of Saxony

Reputation: 22433

It might be easier not to check, line by line and word by word, instead simply check for the word with if (word) in:

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 )

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

Upvotes: 0

Mathias711
Mathias711

Reputation: 6658

Replace 'name'.lower() with name.lower(), because you are now checking with the string name, instead of the variable name.

Upvotes: 1

Related Questions