溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python判斷對(duì)象是否為文件對(duì)象(file object)的三種方法示例

發(fā)布時(shí)間:2020-10-17 17:40:51 來源:腳本之家 閱讀:281 作者:zx 欄目:開發(fā)技術(shù)

文件操作是開發(fā)中經(jīng)常遇到的場(chǎng)景,那么如何判斷一個(gè)對(duì)象是文件對(duì)象呢?下面我們總結(jié)了3種常見的方法。

方法1:比較類型

第一種方法,就是判斷對(duì)象的type是否為file

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

注意:該方法對(duì)于從file繼承而來的子類不適用, 看下面的實(shí)例

class fileDetect(file):
  pass # 中間代碼無所謂,直接跳過不處理
fp2 = fileDetect(r"/tmp/pythontab.com")
fileType = type(fp2)
print(fileType)

結(jié)果:

<class '__main__.fileDetect'>

方法2:isinstance方法

要判斷一個(gè)對(duì)象是否為文件對(duì)象(file object),可以直接用isinstance()判斷。

如下代碼中,open得到的對(duì)象fp類型為file,當(dāng)然是file的實(shí)例,而filename類型為str,自然不是file的實(shí)例

>>> isinstance(fp, file)
True
>>> isinstance(fp2, file)
True
>>> filename = r"/tmp/pythontab.com"
>>> type(filename)
<type 'str'>
>>> isinstance(filename, file)
False

方法3:推測(cè)法

在python中,類型并沒有那么重要,重要的是”接口“。如果它走路像鴨子,叫聲也像鴨子,我們就認(rèn)為它是鴨子(起碼在走路和叫聲這樣的行為上)。

按照這個(gè)思路我們就有了第3中判斷方法:判斷一個(gè)對(duì)象是否具有可調(diào)用的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

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI