【发布时间】:2014-05-22 10:30:24
【问题描述】:
如何检查对象是否为文件?
>>> 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。
【问题讨论】:
-
_io和TextIOWrapper不是全局变量,所以不能直接使用。因此出现错误。 -
不知道
2to3是如何处理这个问题的? -
@smci:我很确定它不会。
fix_types修复程序甚至将FileType映射注释掉。 -
关于如何移植类型检查有什么好的 2 对 3 指南吗?
标签: python class python-3.x