0

I am creating a very basic program that checks if a variable is in a txt file or not, But when I open the txt file and write IF Else statement to python does not read the file.

    f = open("Rdatabase.txt", "r")
        if Lemail in f.read():
            print("Email OK")
        else:
            print("Email not registered")

        if Lpass in f.read():
            print("Pass OK")
        else:
            print("Pass Wrong")

The output of this program is "Email OK" but "Pass Wrong".And when I open the same file with different variable say "A" the output changes to Pass OK. Why is that?

227
  • 11
  • 2
  • 2
    One problem is that each time you call `f.read()` f will point to the end of the file after. So if you call `f.read()` a second time then it will return an empty string. – ssp Dec 12 '20 at 10:05
  • Ok that make sense. But how do I make that 'f.read()' reads the file again without opening the same file again? – 227 Dec 12 '20 at 10:09
  • 2
    Just set a variable equal to what `f.read()` returns and then you're only calling `.read()` one time. – ssp Dec 12 '20 at 10:12
  • 1
    Ok. yeah. Thanks for your help! – 227 Dec 12 '20 at 10:13
  • IndentationError is all I get running this code - you should [edit] the code into the same for that you have in your file locally. Indentation matters in python. – Patrick Artner Dec 12 '20 at 10:51

1 Answers1

0

It's because if you call f.read() a second time then it will return an empty string. You can store f.read() in a variable and call that. Like this:

f = open("Rdatabase.txt", "r")
text = f.read()
if Lemail in text:
    print("Email OK")
else:
    print("Email not registered")

if Lpass in text:
    print("Pass OK")
else:
    print("Pass Wrong")
ppwater
  • 2,315
  • 4
  • 15
  • 29