Reputation: 315
I do not understand why my code is not working. I am writing some very simple code to write a single byte to a file.
with open("foo.txt", "w+", encoding='utf-8') as f:
f.write('\x80')
As you can see below, it ends up writing two bytes when I only want to write one... Can anybody help?
Upvotes: 2
Views: 367
Reputation: 1732
It is 2 bytes because of UTF-8 takes 2 byte places, if you decode it into UTF-16 you will see 4 bytes. They are more than 1 byte because you write it into UTF structure, not as a byte.
You have to open it in binary mode.
with open("foo.txt", "wb+") as f:
f.write(b'\x80')
Upvotes: 1