文件操作是開發中經常遇到的場景,那么如何判斷一個對象是文件對象呢?下面我們總結了3種常見的方法。
方法1:比較類型
第一種方法,就是判斷對象的type是否為file
>>> fp = open(r"/tmp/pythontab.com") >>> type(fp)>>> type(fp) == file True
注意:該方法對于從file繼承而來的子類不適用, 看下面的實例
class fileDetect(file): pass # 中間代碼無所謂,直接跳過不處理 fp2 = fileDetect(r"/tmp/pythontab.com") fileType = type(fp2) print(fileType)
結果:
方法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)>>> isinstance(filename, file) False
方法3:推測法
在python中,類型并沒有那么重要,重要的是”接口“。如果它走路像鴨子,叫聲也像鴨子,我們就認為它是鴨子(起碼在走路和叫聲這樣的行為上)。
按照這個思路我們就有了第3中判斷方法:判斷一個對象是否具有可調用的read,write,close方法(屬性)。
參看:http://docs.python.org/glossary.html#term-file-object
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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
