如何检查对象是否为文件?
>>> 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。