如何以格式刻录字节 Python 3, 不知道编码?

在 Python 2.x 从 'file-like' 目的:


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

并不总是是语义上的文本流。 将其视为字节流有时会有有用的。 例如,
http://www.pixelbeat.org/cmdline.html
:


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


在这种情况下,使用没有意义 Unicode.
已邀请:

知食

赞同来自:

这是一种使用问题 APIs, 哪个与字节一起工作,而不是行。


sys.stdout.buffer.write/bytes_/


如解释说
http://docs.python.org/py3k/li ... stdin
,你也可以
detach

线程,因此默认情况下它们是二进制文件。

这导致访问主字节缓冲区。


tempfile.TemporaryFile//.write/bytes_/


这已经是字节 API.


open/'filename', 'wb'/.write/bytes_/


正如你所期望的那样 'b', 这是字节 API.


from io import BytesIO
BytesIO//.write/bytes_/



BytesIO

- 那个字节等价物
StringIO

.

EDIT:
write

只能与任何人一起工作

二进制

文件对象。 所以一般决定 - 找到右边很容易 API.

郭文康

赞同来自:

指定二进制模式, 'b', 打开文件时:


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


https://docs.python.org/3.3/li ... 3open

要回复问题请先登录注册