我有一串十六进制表示的文本,需要写入文件。
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?
您需要以二进制模式打开文件:
open("example.bin", "wb")
如果没有
b
,您将在文本模式下打开它,这会对您不想要的“换行符”进行一些翻译。
如果您想直接将字节写入文件而不需要本地化的行结束行为,请以二进制模式而不是文本模式打开文件:
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))