1

Please let me know the best way to write 8bit values to a file in python. The values can be between 0 and 255. I open the file as follows:

f = open('temp', 'wb')

Assume the value I am writing is an int between 0 and 255 assigned to a variable, e.g.

x = 13

This does not work:

f.write(x)

..as you experts know does not work. python complains about not being able to write ints to buffer interface. As a work around I am writing it as a hex digit. Thus:

f.write(hex(x))

..and that works but is not only space inefficient but clearly not the right python way. Please help. Thanks.

1

3 Answers 3

3

Try explicitly creating a bytes object:

f.write(bytes([x]))

You can also output a series of bytes as follows:

f.write(bytes([65, 66, 67]))
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks Jim! I really appreciate the example. Much more helpful this way.
1

As an alternative you can use the struct module...

import struct
x = 13
with open('temp', 'wb') as f:
    f.write(struct.pack('>I', x))  # Big-endian, unsigned int

To read x from the file...

with open('temp', 'rb') as f:
    x, = struct.unpack(">I", f.read())

Comments

0

You just need to write an item of bytes data type, not integer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.