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

问题描述 投票:0回答:2

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

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 hex newline
2个回答
0
投票

您需要以二进制模式打开文件:

open("example.bin", "wb")

如果没有

b
,您将在文本模式下打开它,这会对您不想要的“换行符”进行一些翻译。


0
投票

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

toWrite = "020203480A"

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

from pathlib import Path

toWrite = "020203480A"
Path("example.bin").write_bytes(bytes.fromhex(toWrite))
© www.soinside.com 2019 - 2024. All rights reserved.