Python os.closerange()方法

2019-10-16 23:04:17

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!!