当十六进制值为 0x0A 时,停止 python 写入回车符 return

Stop python from writing a carriage return when hex value is 0x0A

我决定重温我的 python,对于第一个项目,我想我会写一个脚本来帮助我完成另一个 class 的作业。对于这个 class,我有一个 excel 传播 sheet 将一些数据转换为十六进制。我通常必须手动将十六进制值输入到我正在使用的程序中,或者我可以从文件中加载二进制数据。

我现在设置的脚本允许我复制传播中的部分 sheet 并将内容复制到一个临时文本文件。当我 运行 我的脚本时,它会创建一个包含二进制数据的文件。它工作除了当我有一个 0x0A 的十六进制值时,因为我将字符串值转换为十六进制的方式将它转换为 '\n' 所以二进制文件有 0D 0A 而不是 0A.

我获取十六进制值的方式:

hexvalue = chr(int(string_value,16))

我写入文件的方式:

f = file("code_out", "w")
for byte in data:
    f.write(byte)
f.close()

这样做的正确方法是什么?

我认为你需要打开文件进行二进制写入!

f = open('file', 'wb')

打开 "binary mode"

中的文件

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written.

即在非"binary mode" in Windows下,当一个"\n"(LF,\x0A)被写入文件流时,实际结果是字节序列" \r\n" (CR LF, \x0D \x0A) 被写入。有关其他说明,请参阅 newline

This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.