【问题标题】:How can I check if an object is a file with isinstance()?如何使用 isinstance() 检查对象是否为文件?
【发布时间】: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。

【问题讨论】:

  • _ioTextIOWrapper 不是全局变量,所以不能直接使用。因此出现错误。
  • 不知道2to3 是如何处理这个问题的?
  • @smci:我很确定它不会。 fix_types 修复程序甚至将FileType 映射注释掉
  • 关于如何移植类型检查有什么好的 2 对 3 指南吗?

标签: python class python-3.x


【解决方案1】:

_ioio module 的 C 实现。导入模块后,直接子类使用io.IOBase

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

【讨论】:

  • 非常感谢@MartijnPieters
  • 如果我想关闭仅文本文件的范围,我可以使用io.TextIOBase吗?
  • 是的,请参阅class hierarchy section,这就是基类的用途(它们是 ABC,因此它们测试功能,而不仅仅是子类)。
猜你喜欢
  • 1970-01-01
  • 2012-06-27
  • 2013-10-11
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 2010-09-27
  • 1970-01-01
相关资源
最近更新 更多