1
votes

I'm pretty new to python, using python 2.7. I have to read in a binary file, and then concatenate some of the bytes together. So I tried

f = open("filename", "rb")
j=0
infile = []
try:
    byte = f.read(1)
    while byte != "":
        infile.append(byte) 
        byte = f.read(1)
finally:
    f.close()
blerg = (bin(infile[8])<<8 | bin(infile[9]))
print type

where I realize that the recast as binary is probably unnecessary, but this is one of my later attempts.

The error I'm getting is TypeError: 'str' object cannot be interpreted as index. This is news to me, since I'm not using a string anywhere. What the !@#% am I doing wrong?

EDIT: Full traceback file binaryExtractor.py, line 25, in blerg = (bin(infile[8])<<8 | bin(infile[9])) TypeError: 'str' object cannot be interpreted as index

2
Please post the full traceback. Also, the indentation is off in the code. And type is a builtin function (or builtin type), so it's better not to use it as variable name. - Lev Levitsky
"since I'm not using a string anywhere": bin returns a string, though. - DSM
I didn't realize bin return a string, I though it gave back the binary format as a number. - bigbenbt

2 Answers

2
votes

You should be using struct whenever possible instead of writing your own code for this.

>>> struct.unpack('<H', '\x12\x34')
(13330,)
1
votes

You want to use the ord function which returns an integer from a single character string, not bin which returns a string representation of a binary number.