Jul-15-2022, 07:46 AM
There is a difference between
Depending on the type, you get different classes from
Here an example to show the different modes and buffered/unbuffered mode.
A
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.