Professor Dragon
Professor Dragon

Reputation: 315

One byte converting to two when written to file

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

Upvotes: 2

Views: 367

Answers (1)

obayhan
obayhan

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

Related Questions