Python将字节字符串写入文件 [英] Python write string of bytes to file

查看:1215
本文介绍了Python将字节字符串写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用python在字节模式下将字节字符串写入文件?

How do I write a string of bytes to a file, in byte mode, using python?

我有:

['0x28', '0x0', '0x0', '0x0']

如何将0x28、0x0、0x0、0x0写入文件?我不知道如何将该字符串转换为有效字节并将其写入。

How do I write 0x28, 0x0, 0x0, 0x0 to a file? I don't know how to transform this string to a valid byte and write it.

推荐答案

映射到 bytearray() bytes()对象,然后将其写入文件:

Map to a bytearray() or bytes() object, then write that to the file:

with open(outputfilename, 'wb') as output:
    output.write(bytearray(int(i, 16) for i in yoursequence))

另一种选择是使用 binascii.unhexlify()函数将十六进制字符串转换为字节值:

Another option is to use the binascii.unhexlify() function to turn your hex strings into a bytes value:

from binascii import unhexlify

with open(outputfilename, 'wb') as output:
    output.write(unhexlify(''.join(format(i[2:], '>02s') for i in b)))

在这里,我们必须先切除 0x 部分,然后重新格式化用零填充它的值,然后将整个值连成一个字符串。

Here we have to chop off the 0x part first, then reformat the value to pad it with zeros and join the whole into one string.

这篇关于Python将字节字符串写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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