【问题标题】:Write a single byte to a file in python 3.x在 python 3.x 中将单个字节写入文件
【发布时间】:2016-01-27 13:42:30
【问题描述】:

在之前的 Python 2 程序中,我使用以下行将单个字节写入二进制文件:

self.output.write(chr(self.StartElementNew))

但是从 Python 3 开始,如果不先将字符串和字符编码为字节,就不能将它们写入流(这对于适当的多字节字符支持是有意义的)

现在有 byte(self.StartElementNew) 之类的吗?如果可能的话,是否兼容 Python 2?

【问题讨论】:

    标签: python file stream binary


    【解决方案1】:

    对于 0-127 范围内的值,以下行将始终在 Python 2 (str) 和 3 (bytes) 中生成正确的类型:

    chr(self.StartElementNew).encode('ascii')
    

    这不适用于 128-255 范围内的值,因为在 Python 2 中,str.encode() 调用包含使用 ASCII 作为编解码器的隐式 str.decode(),这将失败。

    对于 0-255 范围内的字节,我会定义一个单独的函数:

    if sys.version_info.major >= 3:
        as_byte = lambda value: bytes([value])
    else:
        as_byte = chr
    

    然后在写入单个字节时使用它:

    self.output.write(as_byte(self.StartElementNew))
    

    或者,使用six library,它有一个six.int2byte() function;该库为您进行 Python 版本测试,为您提供合适的函数版本:

    self.output.write(six.int2byte(self.StartElementNew))
    

    【讨论】:

    • @galinette:是的,恐怕在编写多语言代码时,并不是所有事情都可以通过捕获ImportErrorNameError 来完成。
    【解决方案2】:

    另一个适用于 Python 2 和 3 的替代方法是使用struct

    import struct
    self.output.write(struct.pack('B', self.StartElementNew))
    

    【讨论】:

      猜你喜欢
      • 2018-04-08
      • 1970-01-01
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多