1

How can I fix AttributeError: 'str' object has no attribute 'read' error in my python3 script.

user = input("Enter your word : ")
script = open('wordlist.txt', "r")

for s in script:
    content = s.read()
    if user in content:
        print("Match")
    else:
        print("Not match")
khelwood
  • 55,782
  • 14
  • 81
  • 108
Dave
  • 15
  • 2
  • 2
    `content = script.read()` and lose the for loop – khelwood Nov 15 '20 at 10:30
  • `read()` is a files' method but you call it on `s` which is a string representing each row of the file. Either change to `if user in s` in the loop or simply `if user in script.read()` – Tomerikoo Nov 15 '20 at 10:33

1 Answers1

0

Try checking for the whole file at once

user = input("Enter your word : ")
script = open('wordlist.txt', "r")

if user in script.read():
    print("Match")
else:
    print("Not match")
Lauwie
  • 16
  • 4
  • Try changing the 'if user in content:' to 'if s in content'. Otherwise it's quite unclear what you are trying to do here. – Lauwie Nov 15 '20 at 10:44
  • How can i iterate text file on loop? Please tell me @Tomerikoo – Dave Nov 15 '20 at 10:45
  • @Dave please try to do some basic research. This is such a common problem in Python with literally thousands of resources online. You have one link above that should help you – Tomerikoo Nov 15 '20 at 10:46
  • @Tomerikoo then he might as well do 'if user in script.readlines():' right? – Lauwie Nov 15 '20 at 10:50
  • @Dave I edited the solution please check if it works now – Lauwie Nov 15 '20 at 10:59