Trimax
Trimax

Reputation: 2473

How can I check if an object is a file with isinstance()?

How can I check if an object is a file?

>>> f = open("locus.txt", "r")
>>> type(f)
<class '_io.TextIOWrapper'>
>>> isinstance(f, TextIOWrapper)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    isinstance(f, TextIOWrapper)
NameError: name 'TextIOWrapper' is not defined
>>> isinstance(f, _io.TextIOWrapper)
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    isinstance(f, _io.TextIOWrapper)
NameError: name '_io' is not defined
>>> isinstance(f, _io)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    isinstance(f, _io)
NameError: name '_io' is not defined
>>> 

I have the variable f that is a text file. When I print the type of f the Python3 interpreter shows '_io.TextIOWrapper', but if I check it with isinstance() function throws exception: NameError.

Upvotes: 14

Views: 7877

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121416

_io is the C implementation for the io module. Use io.IOBase for direct subclasses, after importing the module:

>>> import io
>>> f = open("tests.py", "r")
>>> isinstance(f, io.IOBase)
True

Upvotes: 26

Related Questions