python unhexlify没有按预期工作 [英] python unhexlify not working as expected

查看:345
本文介绍了python unhexlify没有按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当程序打开一个文件时,它都会将该文件视为二进制数据。它将其翻译为更高级的解释性语言,即八进制,十六进制,ASCII码等。在这种情况下,它在LH窗格中显示十六进制,在RH窗格中显示ansi(windows 7,因此它应该是CP1252)。下面的3张图片说明了原始视图,然后是所需的修改,第三张是代码所做的实际更改: $ b






  b data = binascii.hexlify(f.read(160))
如果数据中的数据是旧的:
print'found!'
data = data.replace(old,new)

print'not found'
with open(tar +'new','wb')as:
binascii.unhexlify(data)
fo.write(data)

我显然没有正确地将写入传递方法作为目标。

解决方案

提示:这两行之间有什么区别:

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

binascii.unhexlify(data)
pre>

在Python中,字符串对象是不可变的。没有任何东西可以调用 data ,这会导致 data 名称的字符串发生更改,因为字符串不会更改。 binascii.unhexlify 会返回一个新的字符串 - 这就是为什么第一个语句甚至起作用的原因。如果您想要 .write 产生的新字符串,那么您应该指定在代码中发生 - 直接:

  fo.write(binascii.unhexlify(data))

或者先分配给 data 第一个。


Whenever a program opens a file it sees the file as binary data. It translates it to a higher interpretive language i.e. 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.

这篇关于python unhexlify没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆