python判断文件是否为空文件对象_python坏事Python判断对象是否为文件对象(file object)的三种方法...

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

方法1:比较类型

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

>>> 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方法

《python坏事Python判断对象是否为文件对象(file object)的三种方法》总结了关于python培训教程,对于我们来确实能学到不少知识。

要判断一个对象是否为文件对象(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中,类型并没有那么重要,重要的是”接口“。如果它走路像鸭子,叫声也像鸭子,我们就认为它是鸭子(起码在走路和叫声这样的行为上)。

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

参看:http://docs.python.org/glossary.html#term-file-objectdef 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坏事Python判断对象是否为文件对象(file object)的三种方法

https://www.002pc.comhttps://www.002pc.com/python/2135.html

你可能感兴趣的Python,object,file,对象,三种,文件

No alive nodes found in your cluster

0踩

0 赞

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值