Python os.closerange()方法

Python的os.closerange()方法將關閉所有檔描述符從fd_low(包括)到fd_high(不包括)並忽略錯誤。該方法在Python 2.6版本中引入。

語法

以下是closerange()方法的語法 -

os.closerange(fd_low, fd_high)

參數

  • fd_low − 這是要關閉的最低檔描述符。
  • fd_high − 這是要關閉的最高檔描述符。

此函數實現的功能相當於 -

for fd in xrange(fd_low, fd_high):
   try:
      os.close(fd)
   except OSError:
      pass

返回值

  • 此方法不返回任何值。

示例

以下示例顯示了closerange()方法的用法。

#!/usr/bin/python3
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string
line = "this is test"

# string needs to be converted byte object
b = str.encode(line)
os.write(fd, b)

# Close a single opened file
os.closerange( fd, fd)

print ("Closed all the files successfully!!")

執行上面代碼後,將得到以下結果 -

Closed all the files successfully!!

上一篇: Python os模組方法 下一篇: Python異常處理