---
title: "python判断对象是否为文件对象(file object)"
author: "GhostFromheaven"
date: "2012-07-20T01:44:43Z"
tags: ["GhostFromHeaven", "Python", "file-like object"]
categories: ["编程语言"]
slug: "python-file-object"
draft: false
lastmod: "2012-07-20T01:49:34Z"
id: 1601429
url: "https://ghostfromheaven.iteye.com/blog/1601429"
---

**方法1：比较type**

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

 

**\[python]** [view plain](http://blog.csdn.net/ghostfromheaven/article/details/7765470 "view plain")[copy](http://blog.csdn.net/ghostfromheaven/article/details/7765470 "copy")

01. &gt;&gt;&gt; f = open(r"D:\\2.zip")
02. &gt;&gt;&gt; type(f)
03. &lt;type 'file'&gt;
04. &gt;&gt;&gt; type(f) == file
05. True
06. &gt;&gt;&gt; class MyFile(file):
07. pass
08. &gt;&gt;&gt; mf = MyFile(r"D:\\2.txt")
09. &gt;&gt;&gt; type(mf)
10. &lt;class '\_\_main\_\_.MyFile'&gt;
11. &gt;&gt;&gt; type(mf) == file
12. False

 

**方法2：isinstance**

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

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

 

**\[python]** [view plain](http://blog.csdn.net/ghostfromheaven/article/details/7765470 "view plain")[copy](http://blog.csdn.net/ghostfromheaven/article/details/7765470 "copy")

1. &gt;&gt;&gt; isinstance(f, file)
2. True
3. &gt;&gt;&gt; isinstance(mf, file)
4. True
5. &gt;&gt;&gt; filename = r"D:\\2.zip"
6. &gt;&gt;&gt; type(filename)
7. &lt;type 'str'&gt;
8. &gt;&gt;&gt; isinstance(filename, file)
9. False

 

**方法3：duck like（像鸭子一样）**

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

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

参看：[http://docs.python.org/glossary.html#term-file-object](http://docs.python.org/glossary.html#term-file-object)

 

**\[python]** [view plain](http://blog.csdn.net/ghostfromheaven/article/details/7765470 "view plain")[copy](http://blog.csdn.net/ghostfromheaven/article/details/7765470 "copy")

01. def isfilelike(f):
02. """
03. Check if object 'f' is readable file-like
04. that it has callable attributes 'read' , 'write' and 'closer'
05. """
06. try:
07. if isinstance(getattr(f, "read"), collections.Callable) \\
08. and isinstance(getattr(f, "write"), collections.Callable) \\
09. 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](http://blog.csdn.net/ghostfromheaven/article/details/7765470 "view plain")[copy](http://blog.csdn.net/ghostfromheaven/article/details/7765470 "copy")

01. def isfilelike\_r(f):
02. """
03. Check if object 'f' is readable file-like
04. that it has callable attributes 'read' and 'close'
05. """
06. try:
07. if isinstance(getattr(f, "read"), collections.Callable) \\
08. and isinstance(getattr(f, "close"), collections.Callable):
09. return True
10. except AttributeError:
11. pass
12. return False
13. def isfilelike\_w(f):
14. """
15. Check if object 'f' is readable file-like
16. that it has callable attributes 'write' and 'close'
17. """
18. try:
19. if isinstance(getattr(f, "write"), collections.Callable) \\
20. and isinstance(getattr(f, "close"), collections.Callable):
21. return True
22. except AttributeError:
23. pass
24. return False

**另：为什么用getattr而不是hasattr**

 

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

一方面，hasattr就是直接调用getattr来看是否抛出了AttributeError，如果没有抛出就返回True，否则返回False，[参看这里](http://docs.python.org/library/functions.html#hasattr)。既然如此，我们就可以自己来完成这个工作。

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