文件操做是开发中常常遇到的场景,那么如何判断一个对象是文件对象呢?下面咱们总结了3种常见的方法。
方法1:比较类型
第一种方法,就是判断对象的type是否为file
pythonpython
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中,类型并无那么重要,重要的是“接口”。若是他走路像鸭子,咱们就认为他是鸭子(起码在走路和叫声这样的行为上)。 按照这个思想咱们就有了第三种判断方法:判断一个对象是否有可调用的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