• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python判断对象是否为文件对象(file object)的三种方法示例

python 搞代码 4年前 (2022-01-07) 33次浏览 已收录 0个评论

这篇文章主要介绍了Python判断对象是否为文件对象(file object)的三种方法示例,https://www.pythontab.com/html/2018/pythonhexinbiancheng_1015/1362.html

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

方法1:比较类型

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

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

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

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

结果:

方法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)  >>> isinstance(filename, file) False 

方法3:推测法

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

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

参看:http://docs.python.org/glossary.html#term-file-object

 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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是Python判断对象是否为文件对象(file object)的三种方法示例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python判断对象是否为文件对象(file object)的三种方法示例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址