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

yipeiwu_com5年前Python基础

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

方法1:比较类型

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

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

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

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

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

参看:http://docs.python.org/glossary.html

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python发送邮件功能实现代码

本文实例为大家分享了python发邮件精简代码,供大家参考,具体内容如下 import smtplib from email.mime.text import MIMEText fr...

python制作英语翻译小工具代码实例

这篇文章主要介绍了python制作英语翻译小工具代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 用python爬虫可以制作英语...

解决Django migrate No changes detected 不能创建表的问题

起因 修改了表结构以后执行python3 manage.py migrate 报错: django.db.utils.OperationalError: (1091, "Can't...

python pygame实现挡板弹球游戏

python pygame实现挡板弹球游戏

学了一天pygame,用python和pygame写一个简单的挡板弹球游戏 GitHub: EasyBaffleBallGame # -*- coding:utf-8 -*- fr...

python制作图片缩略图

python制作图片缩略图

缩略图 在很多时候我们都需要将图片按照同比例缩小有利于存储 但是一张张手动去改的话太麻烦了 今天我们就用python实现一个简单的将一个文件夹中的所有图片进行指定大小的调整 缩略前:...