views:

40

answers:

2

I need to detect 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.

+4  A: 

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.

Jeremy Brown
Thanks, Jeremy, I voted your answer but selected the other response because it is a better solution for my problem (let's say that it is more pythonic).
Sorin Sbarnea
+1  A: 

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.

bogdan