温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

判断Python对象是不是为文件对象的方法有哪些

发布时间:2020-08-13 14:01:00 来源:亿速云 阅读:192 作者:小新 栏目:编程语言

这篇文章主要介绍判断Python对象是不是为文件对象的方法有哪些,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

文件操作是开发中经常遇到的场景,那么如何判断一个对象是文件对象呢?下面我们总结了3种常见的方法。

方法1:比较类型

第一种方法,就是判断对象的type是否为file

python
>>> fp = open(r"/tmp/pythontab.com")
>>> type(fp)
<type 'file'>
>>> type(fp) == file
True

注意:该方法对于从file继承而来的子类不适用, 看下面的实例

class fileDetect(file):
    pass # 中间代码无所谓,直接跳过不处理
fp2 = fileDetect(r"/tmp/pythontab.com")
fileType = type(fp2)
print(fileType)

结果:

<class '__main__.fileDetect'>

方法2:isinstance方法

要判断一个对象是否为文件对象(file object),可以直接用isinstance()判断。

如下代码中,open得到的对象fp类型为file,当然是file的实例,而filename类型为str,自然不是file的实例

>>> isinstance(fp, file)
True
>>> isinstance(fp2, file)
True
>>> filename = r"/tmp/pythontab.com"
>>> type(filename)
<type 'str'>
>>> isinstance(filename, file)
False

方法3:推测法

在python中,类型并没有那么重要,重要的是”接口“。如果它走路像鸭子,叫声也像鸭子,我们就认为它是鸭子(起码在走路和叫声这样的行为上)。

按照这个思路我们就有了第3中判断方法:判断一个对象是否具有可调用的read,write,close方法(属性)。

def isfile(f):
    """
    Check if object 'f' is readable file-like 
that it has callable attributes 'read' , 'write' and 'close'
    """
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

以上是判断Python对象是不是为文件对象的方法有哪些的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI