2

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?

Writing two bytes to the file when it should only be writing one

Professor Dragon
  • 217
  • 1
  • 4
  • 14

1 Answers1

1

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')
obayhan
  • 1,636
  • 18
  • 35