pythontypesfilehandleisinstance

What type are file objects in Python?


How can I use isinstance to determine the 'type' of a file object, such as in the expression:

>>> open(file)

Solution

  • These are for use with isinstance.

    In Python 3.x, normal file objects are of type io.TextIOWrapper:

    >>> type(open('file.txt'))
    <class '_io.TextIOWrapper'>
    
    >>> from io import TextIOWrapper
    >>> isinstance(open('file.txt'), TextIOWrapper)
    True
    

    In Python 2.x, all file objects are of type file:

    >>> type(open('file.txt'))
    <type 'file'>
    
    >>> isinstance(open('file.txt'), file)
    True