簡體   English   中英

Python將字節字符串寫入文件

[英]Python write string of bytes to file

如何使用python以字節模式將字節字符串寫入文件?

我有:

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

如何將 0x28、0x0、0x0、0x0 寫入文件? 我不知道如何將此字符串轉換為有效字節並寫入。

映射到bytearray()bytes()對象,然后將其寫入文件:

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

另一種選擇是使用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)))

在這里,我們必須先砍掉0x部分,然后重新格式化該值以用零填充它並將整個連接成一個字符串。

在 Python 3.X 中, bytes()會將整數序列轉換為字節序列:

>>> bytes([1,65,2,255])
b'\x01A\x02\xff'

生成器表達式可用於將您的序列轉換為整數(注意int(x,0)根據其前綴將字符串轉換為整數0x選擇十六進制):

>>> list(int(x,0) for x in ['0x28','0x0','0x0','0x0'])
[40, 0, 0, 0]

組合它們:

>>> bytes(int(x,0) for x in ['0x28','0x0','0x0','0x0'])
b'(\x00\x00\x00'

並將它們寫出來:

>>> 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'

字節如上如何將文件作為字符串寫入文件。 我想在文件中作為打印顯示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM