Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

io - How to write bytes to a file in Python 3 without knowing the encoding?

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

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

How to do the same in Python 3?

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

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

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'

There is no point to use Unicode in this case.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

sys.stdout.buffer.write(bytes_)

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_)

This is already a byte API.

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

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

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

BytesIO is the byte equivalent to StringIO.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...