`
GhostFromheaven
  • 浏览: 393584 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

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

阅读更多

方法1:比较type

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

 

[python] view plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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。

0
3
分享到:
评论

相关推荐

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

    主要介绍了Python判断对象是否为文件对象(file object)的三种方法示例,https://www.pythontab.com/html/2018/pythonhexinbiancheng_1015/1362.html

    python文件处理笔记

    Python的内置Open函数打开一个文件,创建一个file对象,相关的方法可以调用对它进行读写操作 语法:file object = open(filename,access_mode)

    python-处理文本文件.txt

    比如,读取文本文件内容: 如:file_object = open('thefile.txt') # 打开文件 all_the_text = file_object.read( ) # 文本文件的全部文本 file_object.close( ) # 使用完毕,关闭文件 将文本文件的全部内容按照分行...

    Python 读写文件和file对象的方法(推荐)

    1.open 使用open打开文件后...注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。 2.读文件 读文本文件 input = open(‘data’, ‘r’) #第二个参数默认为r input

    从C语言中读取Python 类文件对象

    你要写C扩展来读取来自任何Python类文件对象中的数据(比如普通文件、StringIO对象等)。 解决方案 要读取一个类文件对象的数据,你需要重复调用 read() 方法,然后正确的解码获得的数据。 下面是一个C扩展函数例子...

    Python读写文件方法总结

    本文实例总结了Python读写文件方法。分享给大家供大家参考。具体分析如下: ...注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。 2.读文件 读文本文件 inp

    open的python用法.docx

    它的基本语法如下: ``` file_object = open(file_name, access_mode) ``` 其中,file_name是要打开的文件名,access_mode是打开文件的模式。access_mode有以下几种: - 'r':只读模式,打开文件后只能读取文件内容...

    starryrbs#python_note#python项目-Day12-文件IO1

    Python项目-Day12-文件IO读取文件和写入文件建立通道file object = open(file_name [, access_mode][, b

    用python实现简易文本备份的功能

    用python实现简易文本备份的功能: 主要运用: 1、python的os库 2、文件读写相关操作 """ @author:maoWeiyang @file:yes.py @ide:PyCharm @time:2020/3/1317:57 """ import os import os.path class FileBackup...

    python 文件对象,函数基础,模块基础

    文件对象 文件打开方法 open及file内建函数 1.作为打开文件之门的钥匙”,内建函数open()以及file&#40;&#41;提供了初始化输入/输出( I/O )操作的通用接口 2.成功打开文件后时候会返回一个文件对象,否则引发一个错误 ...

    如何用python处理文件(图文详解)

    用Python处理文件文件的打开文件的关闭文件内容的读取数据的文件写入 ...打开之后将返回一个文件对象(file object),后续对文件内数据的操作都是基于这个文件对象的方法(method)来实现的。 举个例子:

    Python File readlines() 使用方法

    fileObject.readlines( ); 参数 无。 返回值 返回列表,包含所有的行。 实例 以下实例演示了 readline() 方法的使用: 文件jb51.txt 的内容如下: 1:www.jb51.net 2:www.jb51.net 3:www.jb51.net 4:www.jb51.net 5:...

    python之文件的读写和文件目录以及文件夹的操作实现代码

    为了安全起见,最好还是给打开的文件对象指定一个名字,这样在完成操作之后可以迅速关闭文件,防止一些无用的文件对象占用内存。举个例子,对文本文件读取: file_object = open('thefile.txt') try: all_the_text ...

    Python open读写文件实现脚本

    1.open 使用open打开文件后一定...注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。 2.读文件 读文本文件 input = open('data', 'r') #第二个参数默认为r input =

    python学习笔记

    with open('贷款计算.txt') as file_object : contents = file_object.read() print(contents) #10-1 #打印整个文件 with open('123.txt.txt') as file_object : contents=file_object.read() print(contents....

    序列化Python对象的方法

    你需要将一个Python对象序列化为一个字节流,以便将它保存到一个文件、存储到数据库或者通过网络传输它。 解决方案 对于序列化最普遍的做法就是使用 pickle 模块。为了将一个对象保存到一个文件中,可以这样做: ...

    Python——文件的读写

    file_object = open(file_name,access_mode = ‘r’) file_name: 文件路径:相对路径和绝对路径 access_mode: 读 写 读+写 #1.文件打开 fileDir = 'D:/Pytest1.txt' fileDir1 = 'D:\\Pytest2.txt' #最好用两个反斜杠...

    libcusparse.so.11

    OSError: libcusparse.so.11: cannot open shared object file: No such file or directory 搜索全网,也没找到解决方案。最快解决方案如下: 1、在 /home/user/anaconda3/lib/ 中放入缺少的 libcusparse.so.11 文件...

Global site tag (gtag.js) - Google Analytics