john-science / python_for_scientists

Python Open Courseware for Scientists and Engineers
GNU General Public License v3.0
68 stars 40 forks source link

Binary encoding in classes/04_advanced_strings/lecture_04.md #58

Closed XueMChen closed 5 years ago

XueMChen commented 5 years ago

In the Reading and Writing Binary Files section, because binary is a separate type now in Python3, a TypeError will be raised when we try to write character/strings to the binary file: for c in range(50, 70): ... myfile.write(chr(c))

-> TypeError: a bytes-like object is required, not 'str'

After some 'googling', one solution I found was to encode the string first: for c in range(50, 70): ... myfile.write(chr(c).encode())

And once it's read back in, there's a 'b' that shows up in front of the string denoting a binary object: b'23456789:;<=>?@ABCDE'

john-science commented 5 years ago

Thanks Xue! I am looking at it now! I guess I haven't run through this lecture very carefully since making the switch to Python 3 in the past year. Thanks!

john-science commented 5 years ago

Thanks again!

I was able to reproduce your issue in Python 2 and tried you solution in Python 3 and it works like a charm.

It looks like Python 3 makes more explicit the string encoding. You need to manually change the string representation to binary and it adds that little b to tell you it is trying to make a binary string readable. That's a strange change, but it's good to know about. Thanks!