Python What's type for open(file)

Aleeee picture Aleeee · Jul 1, 2014 · Viewed 8.7k times · Source

I want to use isinstance built-in function to judge the type of open(file).

How to do that?

Thanks! :D

Answer

user2555451 picture user2555451 · Jul 1, 2014

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

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

In Python 3.x however, 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
>>>