Searching/reading binary data in Python

前端 未结 8 1880
情歌与酒
情歌与酒 2020-12-25 12:15

I\'m reading in a binary file (a jpg in this case), and need to find some values in that file. For those interested, the binary file is a jpg and I\'m attempting to pick out

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-25 12:59

    For Python >=3.2:

    import re
    
    f = open("filename.jpg", "rb")
    byte = f.read()
    f.close()
    
    matchObj = re.match( b'\xff\xd8.*\xff\xc0...(..)(..).*\xff\xd9', byte, re.MULTILINE|re.DOTALL)
    if matchObj:
        # https://stackoverflow.com/q/444591
        print (int.from_bytes(matchObj.group(1), 'big')) # height
        print (int.from_bytes(matchObj.group(2), 'big')) # width
    

提交回复
热议问题