简体   繁体   中英

python unhexlify not working as expected

Whenever a program opens a file it sees the file as binary data. It translates it to a higher interpretive language ie octal, hex, ascii , etc. In this case it displays hexadecimal in the LH pane and ansi (windows 7 so it should be CP1252) in the RH pane. The 3 pictures below illustrate the original view, then the desired alteration, and the 3rd is the actual change made by the code:

在此输入图像描述

在此输入图像描述

在此输入图像描述

with open(tar,'rb') as f:
data = binascii.hexlify(f.read(160))
if old in data:
    print 'found!'
    data = data.replace(old, new)
else:
    print 'not found'
with open(tar+'new', 'wb') as fo:
    binascii.unhexlify(data)
    fo.write(data)

I have obviously not correctly targeted the write delivery method.

Hint: What is the difference between these two lines:

data = binascii.hexlify(f.read(160))

binascii.unhexlify(data)

In Python, string objects are immutable. There is nothing you can call upon data that will cause the string that data names to change, because strings do not change. binascii.unhexlify instead returns a new string - which is why the first statement even works in the first place. If you wanted to .write the resulting new string, then that's what you should specify to happen in the code - either directly:

fo.write(binascii.unhexlify(data))

or by assigning it back to data first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM