如何检查对象是否是带有isinstance()的文件?

时间:2014-04-09 09:52:04

标签: python class python-3.x

如何检查对象是否为文件?

>>> 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
>>> 

我的变量f是一个文本文件。当我打印出f类型的Python3解释器显示&#39; _io.TextIOWrapper&#39;时,如果我用isinstance()检查它,则抛出异常:NameError。

1 个答案:

答案 0 :(得分:11)

_ioio module的C实现。导入模块后,使用io.IOBase作为直接子类:

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