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

14

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

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


_ioTextIOWrapper不是全局变量,因此您不能直接使用它们。这就是错误的原因。 - Ashwini Chaudhary
我想知道 2to3 如何处理这个问题? - smci
@smci:我非常确定它没有。fix_types修复程序甚至将FileType映射注释掉了。 - Martijn Pieters
有没有关于如何移植类型检查的好的2到3指南? - smci
1个回答

26

_ioio 模块的C实现。导入模块后,请使用 io.IOBase 来直接创建子类:

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

1
非常感谢@MartijnPieters。 - Trimax
1
如果我想仅关闭文本文件的范围,我可以使用 io.TextIOBase 吗? - Trimax
2
是的,请查看类层次结构部分,这就是基类的作用(它们是ABC,因此它们测试功能,而不仅仅是子类)。 - Martijn Pieters

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接