Python Forum

Full Version: writing bytes error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
"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.
I did this:
string1 = 'b"abc123test"'
f = open('file.txt', "wb")
f.write(string1)
f.close()
and it gave the same error
string1 = b"abc123test"
thanks!