简体   繁体   English

Python将字节字符串写入文件

[英]Python write string of bytes to file

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?如何将 0x28、0x0、0x0、0x0 写入文件? I don't know how to transform this string to a valid byte and write it.我不知道如何将此字符串转换为有效字节并写入。

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() function to 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部分,然后重新格式化该值以用零填充它并将整个连接成一个字符串。

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
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我想在文件中作为打印显示

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

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