知行编程网知行编程网  2023-01-10 13:30 知行编程网 隐藏边栏  0 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于如何判断Python对象是否为文件对象?的相关知识,希望可以帮到处于编程学习途中的小伙伴

如何判断 Python 对象是否为文件对象?

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


方法1:比较类型

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

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

注意:该方法不适用于从文件继承的子类,见下面的例子

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中,类型并不是那么重要,重要的是“接口”。如果它走路像鸭子并且叫起来像鸭子,我们就认为它是一只鸭子(至少在像走路和嘎嘎这样的行为上)。

根据这个思路,我们就有了第三种判断方法:判断一个对象是否有可调用的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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享