如何在不知道编码的情况下将字节写入Python 3中的文件? [英] How to write bytes to a file in Python 3 without knowing the encoding?
问题描述
在Python 2.x中使用'file-like'对象:
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 所解释的那样,你也可以 detach
流,因此默认情况下它们是二进制的。
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
。
编辑:写
将只适用于任何二进制文件类对象。所以一般的解决方案就是找到合适的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屋!