os.closerange() 方法



描述

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() 方法的使用。

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

這將建立給定的檔案 foo.txt,然後在該檔案中寫入給定的內容。這將產生以下結果:

Closed all the files successfully!
python_os_file_directory_methods.htm
廣告