开发者

How to assure that filehandle.write() does not fail due to str/bytes conversions issues?

开发者 https://www.devze.com 2023-01-13 17:35 出处:网络
I need to det开发者_StackOverflow社区ect if a filehandle is using binary mode or text mode - this is required in order to be able to encode/decode str/bytes. How can I do that?

I need to det开发者_StackOverflow社区ect if a filehandle is using binary mode or text mode - this is required in order to be able to encode/decode str/bytes. How can I do that?

When using binary mode myfile.write(bytes) works, and when in text mode myfile.write(str) works.

The idea is that I need to know this in order to be able to encode/decode the argument before calling myfile.write(), otherwise it may fail with an exception.


http://docs.python.org/library/stdtypes.html#file.mode

>>> f = open("blah.txt", "wb")
>>> f
<open file 'blah.txt', mode 'wb' at 0x0000000001E44E00>
>>> f.mode
'wb'
>>> "b" in f.mode
True

With this caveat:

file.mode

The I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter. This is a read-only attribute and may not be present on all file-like objects.


How about solving your problem this way:

try:
    f.write(msg)
except TypeError:
    f.write(msg.encode("utf-8"))

This will work even if your handle does not provide a .mode.

0

精彩评论

暂无评论...
验证码 换一张
取 消