-2

I am relatively new to python and was working on a project to enhance my skills, it was a text file compressor; I am having problems with the file scanning portion, I want it to read a text file and find a word. Any help would be much appreciated.

My code:

def check(): 
    datafile = file("res\powerserv 1.txt") 
    for line in datafile: 
        if storage in line: 
            return true 
        else: 
            return false
cs95
  • 379,657
  • 97
  • 704
  • 746
user8480074
  • 1
  • 1
  • 3
  • 2
    Possible duplicate of [Search for string in txt file Python](https://stackoverflow.com/questions/4940032/search-for-string-in-txt-file-python) – cs95 Aug 20 '17 at 04:25
  • I tried that code already it didn't work – user8480074 Aug 20 '17 at 04:26
  • If it didn't work that's because you didn't try it properly. Please post your file and code here indicating what you tried and why it did not work, along with any tracebacks. – cs95 Aug 20 '17 at 04:27
  • What does "didn't work" mean? Why didn't it work? Did it display the wrong data? Did the program crash? – Bryan Oakley Aug 20 '17 at 04:29
  • `def check(): datafile = file("res\powerserv 1.txt") for line in datafile: if storage in line: return true else: return false` – user8480074 Aug 20 '17 at 04:29
  • Yes I think you are correct my code had careless mistakes such as lower case t in True – user8480074 Aug 20 '17 at 04:32

1 Answers1

0

The main issue with your code is the return False inside the for loop.

Assuming this is your file:

word1
word2
word3

You are looking for word3. Now, this is what your program does:

word3 == word1 ? 
No, so break

What you need is:

word3 == word1 ?
No, next iteration

word3 == word2 ?
No, next iteration

word3 == word3 ?
return True

This is how your code should be:

def check(word): 
    with open("res\powerserv 1.txt") as datafile: 
        for line in datafile: 
            if word in line: 
                return True 

    return False

print(check('your word'))

The return False comes outside the loop. Also, consider the use of the with...as context manager to handle opening and closing of your files.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
cs95
  • 379,657
  • 97
  • 704
  • 746