Read binary from file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Read binary from file (/thread-14394.html) |
Read binary from file - nextor - Nov-27-2018 I have some trouble reading binary file with open('myfile', 'rb') as fl: b = fl.read( 1 ) for x in range( 0,4): tuppleCounter[ ( ( 3 << ( x * 2 ) ) & b ) >> ( x*2 ) ]+=1The interpreter says TypeError: unsupported operand type(s) for &: 'int' and 'str' Also b = int( fl.read( 1 ), 10 ) and b = int( fl.read( 1 ) ) for both says ValueError: invalid literal for int() with base 10: 'i' i dont know what im doing wrong RE: Read binary from file - Larz60+ - Nov-27-2018 Please post entire error traceback verbatim supple sample file if possible, or where it can be downloaded b will read 1 byte, starting at byte number 1 in file You don't show tuppleCounter is this what you wanted? You don't need to supply number base to int if decimal If I try with random binary file: >>> with open('image_002.jpg', 'rb') as fp: ... b = fp.read(1) ... >>> b b'\xff' >>> for x in range( 0,4): ... tuppleCounter[ ( ( 3 << ( x * 2 ) ) & b ) >> ( x*2 ) ]+=1 ... Traceback (most recent call last): File "<stdin>", line 2, in <module> NameError: name 'tuppleCounter' is not defined RE: Read binary from file - nextor - Nov-27-2018 if __name__ == "__main__": tuppleCounter = [ 0, 0, 0 ,0 ] with open('myfile', 'rb') as fl: b = fl.read( 1 ) for x in range( 0,4): tuppleCounter[ ( ( 3 << ( x * 2 ) ) & b ) >> ( x*2 ) ]+=1 print tuppleCounter;
RE: Read binary from file - Gribouillis - Nov-27-2018 Are you using PYTHON 2 ????? RE: Read binary from file - nextor - Nov-27-2018 (Nov-27-2018, 08:45 PM)Gribouillis Wrote: Are you using PYTHON 2 ?????it says Python 2.7.15+ And with Python 3.6.7rc1 it says the same RE: Read binary from file - Gribouillis - Nov-27-2018 Python 2 is almost dead (still supported during one year), you should be using python 3.5 or 3.6 or 3.7. You need to convert the char you read to an int. In python 2, do b = fl.read(1) b = ord(b)In python 3, use b = fl.read(1) b = b[0] RE: Read binary from file - nextor - Nov-27-2018 It works, Thanks Gribouillis |