Python3 os.closerange()方法

closerange()方法關閉從 fd_low(含)至 fd_high(不包括)的所有檔描述符,並忽略錯誤。這個方法在 Python2.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!!") 

這將創建指定的檔 foo.txt,然後按給出內容寫入該檔。這將產生以下結果:

Closed all the files successfully!!

上一篇: Python3檔方法 下一篇: Python3 os檔目錄的方法