如何用isinstance()检查对象是否为文件?
我怎么检查一个对象是不是文件呢?
>>> 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 解释器显示的是 '_io.TextIOWrapper',但是如果我用 isinstance()
函数来检查它,就会报错:NameError。