华南俳烁实业有限公司

python

當(dāng)前位置:中華考試網(wǎng) >> python >> python編程基礎(chǔ) >> 文章內(nèi)容

怎樣判斷python對象是否為文件對象?

來源:中華考試網(wǎng)  [2020年9月27日]  【

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

  方法1:比較類型

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

  python

  >>> fp = open(r"/tmp/pythontab.com")

  >>> type(fp)

  >>> type(fp) == file

  True

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

  class fileDetect(file):

  pass # 中間代碼無所謂,直接跳過不處理

  fp2 = fileDetect(r"/tmp/pythontab.com")

  fileType = type(fp2)

  print(fileType)

  結(jié)果:

  

  方法2:isinstance方法

python學(xué)習(xí)課程預(yù)約提醒

  • 地區(qū):
  • 姓名:
  • 手機(jī):

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

  如下代碼中,open得到的對象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)

  

  >>> isinstance(filename, file)

  False

  方法3:推測法

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

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

責(zé)編:hym
  • 會計(jì)考試
  • 建筑工程
  • 職業(yè)資格
  • 醫(yī)藥考試
  • 外語考試
  • 學(xué)歷考試
临城县| 东兴市| 益阳市| 内乡县| 游戏| 滁州市| 五寨县| 和平县| 宜兰县| 泰和县| 乡宁县| 抚州市| 高淳县| 县级市| 伊金霍洛旗| 客服| 抚宁县| 白河县| 区。| 奉新县| 通州市| 高陵县| 合江县| 林周县| 双城市| 兴安县| 长泰县| 门头沟区| 边坝县| 楚雄市| 鸡东县| 宁安市| 吉安市| 常德市| 芜湖县| 江永县| 台湾省| 桃江县| 临夏县| 临汾市| 周宁县|