python判断是不是文件_Python 如何判断对象是否是文件对象

Python2

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

type

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

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

>>> type(f)

>>> type(f) == file

True

>>> class MyFile(file):

... pass

...

>>> mf = MyFile('./text')

>>> type(mf)

>>> 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 中使用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值