Python Forum
writing bytes error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: writing bytes error (/thread-12991.html)



writing bytes error - qrani - Sep-22-2018

When I am writing bytes to a file using this:
string1 = "abc123test"
f = open(filewrite, "wb")
f.write(string1)
f.close()
it gives me this error:
Error:
f.write(string1) TypeError: a bytes-like object is required, not 'str'
can someone help me on this?


RE: writing bytes error - stranac - Sep-22-2018

"abc123test" is a unicode string, b"abc123test" would be bytes.
So either change the type of your variable, or change the mode you open the file in.


RE: writing bytes error - qrani - Sep-22-2018

I did this:
string1 = 'b"abc123test"'
f = open('file.txt', "wb")
f.write(string1)
f.close()
and it gave the same error


RE: writing bytes error - stranac - Sep-22-2018

string1 = b"abc123test"



RE: writing bytes error - qrani - Sep-22-2018

thanks!