如何在不知道编码的情况下将字节写入 Python 3 中的文件? [英] How to write bytes to a file in Python 3 without knowing the encoding?

查看:22
本文介绍了如何在不知道编码的情况下将字节写入 Python 3 中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在带有类文件"对象的 Python 2.x 中:

In Python 2.x with 'file-like' object:

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

如何在 Python 3 中做同样的事情?

How to do the same in Python 3?

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

How to write equivalent of this Python 2.x code:

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

注意:sys.stdout 在语义上并不总是一个文本流.有时将其视为字节流可能会有所帮助.例如,在远程机器上对 dir/进行加密存档:

Note: sys.stdout is not always semantically a text stream. It might be beneficial to consider it as a stream of bytes sometimes. For example, make encrypted archive of dir/ on remote machine:

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

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

There is no point to use Unicode in this case.

推荐答案

这是一个使用对字节而不是字符串进行操作的 API 的问题.

It's a matter of using APIs that operate on bytes, rather than strings.

sys.stdout.buffer.write(bytes_)

正如 docs 解释的那样,您也可以分离 流,因此默认情况下它们是二进制的.

As the docs explain, you can also detach the streams, so they're binary by default.

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

This accesses the underlying byte buffer.

tempfile.TemporaryFile().write(bytes_)

这已经是一个字节 API.

This is already a byte API.

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

正如您对b"所期望的那样,这是一个字节 API.

As you would expect from the 'b', this is a byte API.

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

BytesIO 是等效于 StringIO 的字节.

BytesIO is the byte equivalent to StringIO.

write 将只处理任何二进制 类文件对象.所以一般的解决方案就是找到合适的 API.

write will Just Work on any binary file-like object. So the general solution is just to find the right API.

这篇关于如何在不知道编码的情况下将字节写入 Python 3 中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆