Python将字节字符串写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17349918/
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
Python write string of bytes to file
提问by user2483347
How do I write a string of bytes to a file, in byte mode, using python?
如何使用python以字节模式将字节字符串写入文件?
I have:
我有:
['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.
如何将 0x28、0x0、0x0、0x0 写入文件?我不知道如何将此字符串转换为有效字节并写入。
回答by Martijn Pieters
Map to a bytearray()
or bytes()
object, then write that to the file:
映射到一个bytearray()
或bytes()
对象,然后将其写入文件:
with open(outputfilename, 'wb') as output:
output.write(bytearray(int(i, 16) for i in yoursequence))
Another option is to use the binascii.unhexlify()
functionto turn your hex strings into a bytes
value:
另一种选择是使用该binascii.unhexlify()
函数将您的十六进制字符串转换为一个bytes
值:
from binascii import unhexlify
with open(outputfilename, 'wb') as output:
output.write(unhexlify(''.join(format(i[2:], '>02s') for i in b)))
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.
在这里,我们必须先切掉0x
一部分,然后重新格式化值以用零填充它并将整个连接成一个字符串。
回答by Mark Tolonen
In Python 3.X, bytes()
will turn an integer sequence into a bytes sequence:
在 Python 3.X 中,bytes()
会将整数序列转换为字节序列:
>>> bytes([1,65,2,255])
b'\x01A\x02\xff'
A generator expression can be used to convert your sequence into integers (note that int(x,0)
converts a string to an integer according to its prefix. 0x
selects hex):
生成器表达式可用于将您的序列转换为整数(请注意,int(x,0)
根据前缀将字符串转换为整数。 0x
选择十六进制):
>>> list(int(x,0) for x in ['0x28','0x0','0x0','0x0'])
[40, 0, 0, 0]
Combining them:
组合它们:
>>> bytes(int(x,0) for x in ['0x28','0x0','0x0','0x0'])
b'(\x00\x00\x00'
And writing them out:
并将它们写出来:
>>> L = ['0x28','0x0','0x0','0x0']
>>> with open('out.dat','wb') as f:
... f.write(bytes(int(x,0) for x in L))
...
4
回答by stevenxu
b=b'\xac\xed\x00\x05sr\x00\x0emytest.ksiazka\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x03L\x00\x05autort\x00\x12Ljava/lang/String;L\x00\x03rokt\x00\x13Ljava/lang/Integer;L\x00\x05tytulq\x00~\x00\x01xpt\x00\x04testpp'
bytes as above how to write to file as string. i want as print show in the file
字节如上如何将文件作为字符串写入文件。我想在文件中作为打印显示