Python 将十六进制数据写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26796770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:01:59  来源:igfitidea点击:

Writing hex data into a file

pythonstringfilebinaryhex

提问by Pythonizer

I'm trying to write hex data taken from ascii file to a newly created binary file

我正在尝试将从 ascii 文件中获取的十六进制数据写入新创建的二进制文件

ascii file example:

ascii 文件示例:

98 af b7 93 bb 03 bf 8e ae 16 bf 2e 52 43 8b df
4f 4e 5a e4 26 3f ca f7 b1 ab 93 4f 20 bf 0a bf
82 2c dd c5 38 70 17 a0 00 fd 3b fe 3d 53 fc 3b
28 c1 ff 9e a9 28 29 c1 94 d4 54 d4 d4 ff 7b 40

my code

我的代码

hexList = []
with open('hexFile.txt', 'r') as hexData:
    line=hexData.readline()
    while line != '':
        line = line.rstrip()
        lineHex = line.split(' ')
        for i in lineHex:
            hexList.append(int(i, 16))
        line = hexData.readline()


with open('test', 'wb') as f:
    for i in hexList:
        f.write(hex(i))

Thought hexListholds already hex converted data and f.write(hex(i))should write these hex data into a file, but python writes it with ascii mode

ThoughthexList已经保存了 hex 转换的数据,f.write(hex(i))应该将这些 hex 数据写入文件中,但是 python 以 ascii 方式写入

final output: 0x9f0x2c0x380x590xcd0x110x7c0x590xc90x30xea0x37which is wrong!

最终输出:0x9f0x2c0x380x590xcd0x110x7c0x590xc90x30xea0x37这是错误的!

where is the issue?

问题出在哪里?

采纳答案by falsetru

Use binascii.unhexlify:

使用binascii.unhexlify

>>> import binascii
>>> binascii.unhexlify('9f')
'\x9f'

>>> hex(int('9f', 16))
'0x9f'


import binascii

with open('hexFile.txt') as f, open('test', 'wb') as fout:
    for line in f:
        fout.write(
            binascii.unhexlify(''.join(line.split()))
        )

回答by John1024

replace:

代替:

    f.write(hex(i))

With:

和:

    f.write(chr(i))  # python 2

Or,

或者,

    f.write(bytes((i,))) # python 3

Explanation

解释

Observe:

观察:

>>> hex(65)
'0x41'

65should translate into a single byte but hexreturns a four character string. writewill send all four characters to the file.

65应该转换为单个字节,但hex返回一个四个字符的字符串。 write将所有四个字符发送到文件。

By contrast, in python2:

相比之下,在python2中:

>>> chr(65)
'A'

This does what you want: chrconverts the number 65to the character single-byte string which is what belongs in a binary file.

这可以满足您的需求:chr将数字转换65为属于二进制文件的字符单字节字符串。

In python3, chr(i)is replaced by bytes((i,)).

在 python3 中,chr(i)被替换为bytes((i,)).