Python 如何判断对象是否是文件对象

Python2

Python2 有一种比较可靠的方式就是判断对象的类型是否是file类型。因此可以使用type函数或者isinstance函数实现。

type

当然type函数无法对继承得来的子类起作用

>>> f = open('./text', 'w')
>>> type(f)
<type 'file'>
>>> type(f) == file
True

>>> class MyFile(file):
...     pass
...
>>> mf = MyFile('./text')
>>> type(mf)
<class '__main__.MyFile'>
>>> type(mf) == file
False

isinstance

isinstancne是推荐的判断类型时方法,通常情况下都应该选择此方法。isinstance也可以对子类起作用。

>>> f = open('./text', 'w')
>>> isinstance(f, file)
True

>>> class MyFile(file):
...     pass
...
>>> mf = MyFile('./text')
>>> isinstance(mf, file)
True

Python3

在 Python3 中,官方取消了file这一对象类型,使得 python2 中的判断方法无法在 Python3 中使用。

因此在 Python3 中只能通过鸭子类型的概念判断对象是否实现了可调用的``read, write, close方法, 来判断对象是否是一个文件对象了。

def isfilelike(f):
    try:
        if isinstance(getattr(f, "read"), collections.Callable) \
                and isinstance(getattr(f, "write"), collections.Callable) \
                and isinstance(getattr(f, "close"), collections.Callable):

            return True
    except AttributeError:
        pass

    return False

当然这个方法也可以在 python2 中使用

posted @ 2020-12-03 15:19  暮晨  阅读(766)  评论(0编辑  收藏  举报

Aaron Swartz was and will always be a hero