How to determine if a file is open in binary or text mode?

Given a file object, how do I determine if it is open in byte mode ( readreturns bytes) or in text mode ( readreturns str)? He should work with reading and writing.

In other words:

>>> with open('filename', 'rb') as f:
...     is_binary(f)
...
True

>>> with open('filename', 'r') as f:
...     is_binary(f)
...
False

( Another question that sounds related wrong. This question is assuming whether the file is binary or not from it.)

+4
source share
3 answers

File objects have an attribute .mode:

def is_binary(f):
    return 'b' in f.mode

, , TextIO BytesIO, . :

import io

def is_binary(f):
    return isinstance(f, (io.RawIOBase, io.BufferedIOBase))

def is_binary(f):
    return not isinstance(f, io.TextIOBase)
+10

, , , :

def is_binary(f):
    return isinstance(f.read(0), bytes)

, , ( IOError), , io ABC, mode.

Python 3, / , :

def is_binary(f):
    read = getattr(f, 'read', None)
    if read is not None:
        try:
            data = read(0)
        except (TypeError, ValueError):
            pass # ValueError is also a superclass of io.UnsupportedOperation
        else:
            return isinstance(data, bytes)
    try:
        # alternatively, replace with empty text literal
        # and swap the following True and False.
        f.write(b'')
    except TypeError:
        return False
    return True

, ( , ), , , catching (, , likelier).

0

, mimetypes, guess_type - (, ), type - None, can not ( ) 'type/subtype

import mimetypes
file= mimetypes.guess_type(file)
-2

Source: https://habr.com/ru/post/1679425/


All Articles