0

I have a text file (buy_sell.txt) containing the word "BOUGHT". No new lines or spaces.

When I try to check if the contents of the file ("BOUGHT") are equal to "BOUGHT" it evaluates to false!

  f = open("buy_sell.txt", "r")
  print(f.read())
  if(f.read() == "BOUGHT"):
    print('works')

How do I get the code to evaluate to true?

2
  • 5
    The second f.read() will give you ''. Commented Apr 12, 2020 at 14:47
  • 1
    The cursor of the file is at the end after you used f.read(). Commented Apr 12, 2020 at 14:49

1 Answer 1

4

Since your file is a single line, you just need to read it once:

f = open("buy_sell.txt", "r")
if f.read() == "BOUGHT":
    print("works")

If you would like to reuse this value later on, just assign it to a variable:

f = open("buy_sell.txt", "r")
my_value = f.read()
if my_value == "BOUGHT":
    print("works")

if my_value != "BOUGHT": 
   print("Must be SOLD!")

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I thought there was an invisible character read from the file or something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.