如何在不知道编码的情况下将字节写入 Python 3 中的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4290716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write bytes to a file in Python 3 without knowing the encoding?
提问by jfs
In Python 2.x with 'file-like' object:
在带有“类文件”对象的 Python 2.x 中:
sys.stdout.write(bytes_)
tempfile.TemporaryFile().write(bytes_)
open('filename', 'wb').write(bytes_)
StringIO().write(bytes_)
How to do the same in Python 3?
如何在 Python 3 中做同样的事情?
How to write equivalent of this Python 2.x code:
如何编写与此 Python 2.x 代码等效的代码:
def write(file_, bytes_):
file_.write(bytes_)
Note: sys.stdoutis 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:
注意:sys.stdout在语义上并不总是文本流。有时将其视为字节流可能会有所帮助。例如,在远程机器上对 dir/ 进行加密存档:
tar -c dir/ | gzip | gpg -c | ssh user@remote 'dd of=dir.tar.gz.gpg'
There is no point to use Unicode in this case.
在这种情况下使用 Unicode 毫无意义。
采纳答案by Matthew Flaschen
It's a matter of using APIs that operate on bytes, rather than strings.
这是使用对字节而不是字符串进行操作的 API 的问题。
sys.stdout.buffer.write(bytes_)
As the docsexplain, you can also detachthe streams, so they're binary by default.
正如文档所解释的,您也可以detach使用流,因此默认情况下它们是二进制的。
This accesses the underlying byte buffer.
这将访问底层字节缓冲区。
tempfile.TemporaryFile().write(bytes_)
This is already a byte API.
这已经是一个字节 API。
open('filename', 'wb').write(bytes_)
As you would expect from the 'b', this is a byte API.
正如您对“b”所期望的那样,这是一个字节 API。
from io import BytesIO
BytesIO().write(bytes_)
BytesIOis the byte equivalent to StringIO.
BytesIO是等效于 的字节StringIO。
EDIT: writewill Just Work on any binaryfile-like object. So the general solution is just to find the right API.
编辑:write将只适用于任何二进制文件类对象。所以一般的解决方案就是找到合适的 API。
回答by bigonazzi
Specify binary mode, 'b', when you open your file:
打开文件时指定二进制模式“b”:
with open('myfile.txt', 'wb') as w:
w.write(bytes)

