Python Forum

Full Version: supporting both str and bytes on write file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
There is a difference between str and bytes. In addition, bytes could be unbuffered.
Depending on the type, you get different classes from io module back.

Here an example to show the different modes and buffered/unbuffered mode.
for mode, buffering in (("r", -1), ("rb", -1), ("w", -1), ("wb", -1), ("rb", 0), ("wb", 0)):
    with open("/dev/null", mode, buffering=buffering) as fd:
        bytes_mode = not hasattr(fd, "encoding")
        if bytes_mode:
            print(type(fd), "MODE:", fd.mode, "bytes")
        else:
            print(type(fd), "MODE:", fd.mode, "str")
Output:
<class '_io.TextIOWrapper'> MODE: r str <class '_io.BufferedReader'> MODE: rb bytes <class '_io.TextIOWrapper'> MODE: w str <class '_io.BufferedWriter'> MODE: wb bytes <class '_io.FileIO'> MODE: rb bytes <class '_io.FileIO'> MODE: wb bytes
PS:
A FileObject which was opened in raw mode, does not have the encoding attribute.
so, where do i get the value of mode and buffering from? is there an attribute in the file object?
i see where i asked in a confusing way. the open i want to do is my own class of object over another, so it can accept an already-open object as the "name" argument.
Pages: 1 2