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异常处理