Python如何在二进制模式下编写十六进制列表?

Python how to write in binary mode a list of hexadecimals?

提问人:mine_greg 提问时间:9/16/2023 更新时间:9/16/2023 访问量:27

问:

我有一串十六进制的文本表示形式,我需要将其写入文件。

toWrite = "020203480A"

with open("example.bin", "w") as file:
   file.write(chr(int(toWrite, 16)))

问题是,每当我编写 LF (0A) 时,Windows 都会自动添加 CR (0D)。我知道,因为我在 HxD 中打开文件,我读了.02 02 03 48 0D 0A

如何防止 Windows 在 LF 之前添加 CR?

python-3.x Windows 十六进制 换行符

评论

0赞 Brian61354270 9/16/2023
您能否准确说明您打算向文件写入的内容?您是否正在尝试写入由十六进制表示编码的字节?toWrite

答:

1赞 Brian61354270 9/16/2023 #1

如果要直接将字节写入文件而不使用本地化的行结束行为,请以二进制模式而不是文本模式打开文件:

toWrite = "020203480A"

# Note "wb" instead of "w"
with open("example.bin", "wb") as file:
   file.write(bytes.fromhex(toWrite))

或者,使用 pathlib 自动处理打开和关闭文件:

from pathlib import Path

toWrite = "020203480A"
p = Path("example.bin")
p.write_bytes(bytes.fromhex(toWrite))
0赞 xPetersue 9/16/2023 #2

您应该在“wb”模式下打开文件,这将以二进制模式打开文件,从而防止 Windows 在 LF 之前自动插入 CR。

toWrite = "020203480A"

with open("example.bin", "wb") as file:
    file.write(bytes.fromhex(toWrite))

注意:bytes.fromhex(toWrite) 将十六进制字符串转换为 bytes 对象,并按原样将其写入文件。

当您在 HxD 中打开“example.bin”时,您应该会看到如下内容:

02 02 03 48 0A