Python 檔案 fileno() 方法



Python 檔案的 fileno() 方法返回開啟檔案的檔案描述符(或檔案控制代碼)。檔案描述符是一個無符號整數,作業系統使用它來識別 os 核心中的開啟檔案。它只儲存非負值。

檔案描述符就像用於獲取儲存在資料庫中的記錄的 ID。因此,Python 使用它對檔案執行各種操作;例如開啟檔案、寫入檔案、從檔案讀取或關閉檔案等。

語法

以下是 Python 檔案 fileno() 方法的語法:

fileObject.fileno(); 

引數

該方法不接受任何引數。

返回值

此方法返回整數檔案描述符。

示例

以下示例顯示了 Python 檔案 fileno() 方法的使用。在這裡,我們嘗試使用檔案物件以寫入二進位制 (wb) 模式開啟檔案“foo.txt”。然後,在該檔案物件上呼叫 fileno() 方法以檢索引用當前檔案的檔案描述符。

# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)

fid = fo.fileno()
print("File Descriptor: ", fid)

# Close opened file
fo.close()

當我們執行上面的程式時,它會產生以下結果:

Name of the file:  foo.txt
File Descriptor:  3

示例

檔案描述符也用於關閉它所代表的檔案。

在此示例中,我們正在匯入 os 模組,因為檔案描述符通常由作業系統維護。由於我們使用檔案物件來引用檔案,因此在代表當前檔案的檔案物件上呼叫 fileno() 方法以檢索其檔案描述符。透過將檢索到的檔案描述符作為引數傳遞給 os.close() 方法來關閉檔案。

import os
# Open a file using a file object 'fo'
fo = open("hi.txt", "w")

fid = fo.fileno()
print("The file descriptor of the given file: ", str(fid))

# Close the opened file
os.close(fid)

如果我們編譯並執行上面的程式,則結果如下所示:

The file descriptor of the given file:  3

示例

但是,如果檔案不存在並且程式仍然嘗試以讀取模式開啟它,則 fileno() 方法會引發 FileNotFoundError。

fo = open("hi.txt", "r")

# Return the file descriptor
fid = fo.fileno()

# Display the file descriptor
print(fid)

#Close the opened file
fo.close()

編譯並執行上面的程式,獲得的輸出如下:

Traceback (most recent call last):
  File "D:\Tutorialspoint\Programs\Python File Programs\filenodemo.py", line 1, in 
    fo = open("hi.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'hi.txt'
python_file_methods.htm
廣告