如何用isinstance()检查对象是否为文件?

14 投票
1 回答
7503 浏览
提问于 2025-04-18 02:00

我怎么检查一个对象是不是文件呢?

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

1 个回答

26

_io 是 C 语言实现的 io 模块。在导入这个模块后,可以使用 io.IOBase 来直接使用它的子类:

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

撰写回答