1

The content of my text file is:

5 7 6 6 15
4 3

When I do

fs.open('path',mode='rb').read()

I get

b'5 7 6 6 15\r\n4 3'

But because I want it to compare to string output

5 7 6 6 15
4 3

I want to do this comparison like :

if fs.open('path',mode='rb').read() == output
    print("yes")

How should I convert it in way that line breaks space everything is maintained?

PS: output is just the string that I am getting through json.

5
  • 1
    When you want a string, why do you read the file in binary mode? Commented Nov 29, 2017 at 15:08
  • maybe drop binary mode you'll get 2 same objects Commented Nov 29, 2017 at 15:08
  • 1
    I think it's because you read it with binary mode 'rb'. What if you try 'r'? Commented Nov 29, 2017 at 15:08
  • 1
    it's unclear if the last line contains a newline or not. This could make the comparison fail. Commented Nov 29, 2017 at 15:10
  • Last line contains newline, ok guys i ll try the r mode and let you know. Thank you so much. Commented Nov 29, 2017 at 15:21

2 Answers 2

1

Using Python 3, fs.open('path',mode='rb').read() yields a bytes object, moreover containing a carriage return (windows text file)

(and using Python 2 doesn't help, because of this extra \r which isn't removed because of binary mode)

You're comparing a bytes object with a str object: that is always false.

Moreover, it's unclear if the output string has a line termination on the last line. I would open the file in text mode and strip blanks/newline the end (the file doesn't seem to contain one, but better safe than sorry):

with open('path') as f:
   if f.read().rstrip() == output.rstrip():
Sign up to request clarification or add additional context in comments.

Comments

1

Change the read mode from rb to r: rb gives back binary, r puts out text.

Comments

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.