简体   繁体   English

python unhexlify没有按预期工作

[英]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. 它将它转换为更高的解释语言,即八进制,十六进制,ascii等。在这种情况下,它在RH窗格中显示十六进制,在RH窗格中显示ansi(窗口7,因此它应该是CP1252)。 The 3 pictures below illustrate the original view, then the desired alteration, and the 3rd is the actual change made by the code: 下面的3张图片说明了原始视图,然后是所需的更改,第3张是代码所做的实际更改:

在此输入图像描述

在此输入图像描述

在此输入图像描述

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. 在Python中,字符串对象是不可变的。 There is nothing you can call upon data that will cause the string that data names to change, because strings do not change. 没有什么可以调用时data ,这将导致字符串data的名称改变,因为字符串没有改变。 binascii.unhexlify instead returns a new string - which is why the first statement even works in the first place. 而不是binascii.unhexlify返回一个字符串 - 这就是为什么第一个语句甚至首先起作用的原因。 If you wanted to .write the resulting new string, then that's what you should specify to happen in the code - either directly: 如果你想.write生成的新字符串,那么你应该在代码中指定这一点 - 直接:

fo.write(binascii.unhexlify(data))

or by assigning it back to data first. 或者首先将其分配回data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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