0

I am new to python and I am trying to use unpack like this:

data = f.read(4)
AAA=len(data)
BBB=struct.calcsize(cformat)
print AAA
print BBB
value = struct.unpack(cformat, data)
return value[0]

This runs fine as long as AAA == BBB but sometimes, f.read only reads 3 bytes and then I get an error. The actual value in the file that I am trying to read is 26. It reads all of the values from 1-221 except for 26 where it errors because f.read(size) only reads three bytes

Bhargav Rao
52.6k29 gold badges130 silver badges142 bronze badges
asked Apr 1, 2015 at 18:11
1
  • You have described what happens and why. Do you have a question? Commented Apr 1, 2015 at 18:15

2 Answers 2

1

Assuming the question is "How should I read a 26 without an error?"

First check the arguments to the open() that produces f. Under Windows, unless you open a file in binary mode (f = open(filename, "rb")), Python assumes that the file is a text file. Windows treats byte value 26 (Ctrl+Z) in a text file as an end-of-file marker, a quirk that it inherited from CP/M.

answered Apr 1, 2015 at 18:17
Sign up to request clarification or add additional context in comments.

Comments

0

You have opened a binary file in text mode, and you are using an operating system where the distinction matters. Try adding b to the mode parameter when you open the file:

f = open("my_input_file.bin", "rb")
answered Apr 1, 2015 at 18:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.