脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python判断对象是否为文件对象(file object)的三种方法示例

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

2021-06-20 00:35pythontab Python

这篇文章主要介绍了Python判断对象是否为文件对象(file object)的三种方法示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

方法1:比较类型

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

?
1
2
3
4
5
>>> fp = open(r"/tmp/pythontab.com")
>>> type(fp)
<type 'file'>
>>> type(fp) == file
true

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

?
1
2
3
4
5
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的实例

?
1
2
3
4
5
6
7
8
9
>>> isinstance(fp, file)
true
>>> isinstance(fp2, file)
true
>>> filename = r"/tmp/pythontab.com"
>>> type(filename)
<type 'str'>
>>> isinstance(filename, file)
false

方法3:推测法

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

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

参看:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.pythontab.com/html/2018/pythonhexinbiancheng_1015/1362.html

延伸 · 阅读

精彩推荐