首页 > 解决方案 > 二进制模式下的 Python 3 open() 未写入正确的内容

问题描述

所以基本上,我在使用 python3 写入字节时遇到问题。我已通过使用 print 确保内容符合预期,但它仍在写入不正确的内容。它基本上将第一行复制了 4 次。我正在使用拉丁语1。本质上,我在 b 字符串中包含的唯一原始字节是0x800x81(即\x80\x81)。"wb"我在模式下使用 building open() 函数编写它。有人知道发生了什么吗?

编辑:这是用于创建文件的主要方法。如前所述,fs 是以 wb 模式打开的文件,它按预期打印。

    def assemble_file(self, fs):
        "must call lex_from_asm_text before assembling"
        self.bin_raw_content += b"ROSAPYVM\x81"
        for x in self._asm_stripped:
            try:
                bcode = bytes([ops.__dict__[x[0]]])
                print(bcode)
                print([x[1:]])
                self.bin_raw_content += b"\x00"
                self.bin_raw_content += bcode
                for i in x[1:]:
                    self.bin_raw_content += b"\x80"
                    print(i.encode("latin-1"))
                    self.bin_raw_content += i.encode("latin-1")
            except IndexError:
                pass
            print(self.bin_raw_content)

            fs.write(self.bin_raw_content)

标签: python-3.xiso-8859-1

解决方案


推荐阅读