python判断对象是否为文件对象(file object)

本文详细介绍了在Python中如何判断一个对象是否为文件对象,包括使用type、isinstance及ducklike方法。同时讨论了如何根据不同的操作需求来判断类文件对象的特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法1:比较type

第一种方法,就是判断对象的type是否为file,但该方法对于从file继承而来的子类不适用

 

[python]   view plain copy
  1. >>> f = open(r"D:\2.zip")  
  2. >>> type(f)  
  3. <type 'file'>  
  4. >>> type(f) == file  
  5. True  
  6. >>> class MyFile(file):  
  7.     pass  
  8.   
  9. >>> mf = MyFile(r"D:\2.txt")  
  10. >>> type(mf)  
  11. <class '__main__.MyFile'>  
  12. >>> type(mf) == file  
  13. False  

 

方法2:isinstance

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

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

 

[python]   view plain copy
  1. >>> isinstance(f, file)  
  2. True  
  3. >>> isinstance(mf, file)  
  4. True  
  5. >>> filename = r"D:\2.zip"  
  6. >>> type(filename)  
  7. <type 'str'>  
  8. >>> isinstance(filename, file)  
  9. False  

 

方法3:duck like(像鸭子一样)

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

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

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

 

[python]   view plain copy
  1. def isfilelike(f):  
  2.     """ 
  3.     Check if object 'f' is readable file-like  
  4.     that it has callable attributes 'read' , 'write' and 'closer' 
  5.     """  
  6.     try:  
  7.         if isinstance(getattr(f, "read"), collections.Callable) \  
  8.             and isinstance(getattr(f, "write"), collections.Callable) \  
  9.                 and isinstance(getattr(f, "close"), collections.Callable):  
  10.             return True  
  11.     except AttributeError:  
  12.         pass  
  13.     return False  


 

其他:读/写方式打开的”类文件“对象

只从文件读入数据的时候只要检查对象是否具有read,close;相应的只往文件中写入数据的时候仅需要检查对象是否具有write,close方法。就像如果仅从走路方式判断它是否为鸭子,只检查是否”走路像鸭子“;如果仅从声音来判断,则仅需要检查是否”叫声像鸭子“。

 

[python]   view plain copy
  1. def isfilelike_r(f):  
  2.     """ 
  3.     Check if object 'f' is readable file-like  
  4.     that it has callable attributes 'read' and 'close' 
  5.     """  
  6.     try:  
  7.         if isinstance(getattr(f, "read"), collections.Callable) \  
  8.             and isinstance(getattr(f, "close"), collections.Callable):  
  9.             return True  
  10.     except AttributeError:  
  11.         pass  
  12.     return False  
  13.   
  14. def isfilelike_w(f):  
  15.     """ 
  16.     Check if object 'f' is readable file-like  
  17.     that it has callable attributes 'write' and 'close' 
  18.     """  
  19.     try:  
  20.         if isinstance(getattr(f, "write"), collections.Callable) \  
  21.             and isinstance(getattr(f, "close"), collections.Callable):  
  22.             return True  
  23.     except AttributeError:  
  24.         pass  
  25.     return False  

另:为什么用getattr而不是hasattr

 

这里为什么不用hasattr,而是用getattr来承担抛出AttributeError的风险呢?

一方面,hasattr就是直接调用getattr来看是否抛出了AttributeError,如果没有抛出就返回True,否则返回False,参看这里。既然如此,我们就可以自己来完成这个工作。

另一方面,这样我们可以得到属性对象,然后可以用isinstance判断是否为collections.Callable的实例。两者结合,如果有该属性,并可以被调用,则返回True。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值