代码之家  ›  专栏  ›  技术社区  ›  jfs

如何在不知道编码的情况下将字节写入python 3中的文件?

  •  40
  • jfs  · 技术社区  · 14 年前

    在具有“类似文件”对象的python 2.x中:

    sys.stdout.write(bytes_)
    tempfile.TemporaryFile().write(bytes_)
    open('filename', 'wb').write(bytes_)
    StringIO().write(bytes_)
    

    如何在python 3中执行相同的操作?

    如何编写与此python 2.x代码等效的代码:

    def write(file_, bytes_):
        file_.write(bytes_)
    

    注: sys.stdout 在语义上并不总是文本流。有时将其视为字节流可能是有益的。例如, make encrypted archive of dir/ on remote machine :

    tar -c dir/ | gzip | gpg -c | ssh user@remote 'dd of=dir.tar.gz.gpg'
    

    在这种情况下,没有必要使用Unicode。

    2 回复  |  直到 9 年前
        1
  •  50
  •   Matthew Flaschen    14 年前

    这是一个使用字节而不是字符串操作的API的问题。

    sys.stdout.buffer.write(bytes_)
    

    作为 docs 解释一下,你也可以 detach 流,所以默认情况下它们是二进制的。

    这将访问底层字节缓冲区。

    tempfile.TemporaryFile().write(bytes_)
    

    这已经是一个字节API。

    open('filename', 'wb').write(bytes_)
    

    正如您对“b”所期望的那样,这是一个字节API。

    from io import BytesIO
    BytesIO().write(bytes_)
    

    BytesIO 字节等于 StringIO .

    编辑: write 只对任何 二元的 类似文件的对象。所以一般的解决方案就是找到正确的API。

        2
  •  16
  •   bigonazzi    9 年前

    打开文件时,请指定二进制模式“b”:

    with open('myfile.txt', 'wb') as w:
        w.write(bytes)
    

    https://docs.python.org/3.3/library/functions.html#open