Python os.close() 方法



Python os.close() 方法關閉指定的 檔案描述符。Python 中的檔案描述符是識別符號,代表作業系統核心中開啟的檔案,並儲存在檔案表中。

通常,檔案描述符具有非負值。負結果表示錯誤或“無值”情況。它們主要用於訪問檔案和其他輸入/輸出裝置,例如網路套接字或管道。

語法

以下是 Python os.close() 方法的語法:

os.close(fd);

引數

  • fd − 這是檔案的 檔案描述符。

返回值

此方法不返回值。

示例 1

以下示例顯示了 Python os.close() 方法的用法。在這裡,我們建立了一個檔案描述符 'os.O_RDWR|os.O_CREAT'。然後,我們在檔案中寫入字串“This is test”。之後,我們使用此方法關閉檔案。

import os, sys

# Open a file
fd = os.open("foo.txt", os.O_RDWR|os.O_CREAT)
# Write one string
string = "This is test"
x = str.encode(string)
os.write(fd,x)
# Close opened file
os.close(fd)
print ("Closed the file successfully!!")

執行上述程式時,會產生以下結果:

Closed the file successfully!!

示例 2

在下面給出的示例中,我們建立了一個檔案描述符 'r'。這意味著讀取檔案。

import os
file = "code.txt"
file_Object = open(file, "r")
fd = file_Object.fileno()
print("The descriptor of the file for %s is %s" % (file, fd))
os.close(fd)

執行上述程式碼時,我們得到以下輸出:

The descriptor of the file for code.txt is 3

示例 3

如果檔案描述符無效,則此方法會引發 EBADF 錯誤。

import os
# Creating a file descriptor
filedesc = os.open("code.txt", os.O_RDWR)
# closing an invalid file descriptor
os.close(filedesc + 1)

以下是上述程式碼的輸出:

Traceback (most recent call last):
  File "/home/sarika/Desktop/chown.py", line 5, in <module>
    os.close(filedesc + 1)
OSError: [Errno 9] Bad file descriptor
os_file_methods.htm
廣告