fileno() 方法回傳檔案物件對應的整數檔案描述符。檔案描述符是作業系統核心用來識別開啟檔案的非負整數,可用於底層 I/O 操作(os.read/os.write)、select/poll 多工監控、mmap 記憶體映射、fcntl 檔案鎖定等進階場景。
語法
fileObject.fileno()
- 無參數。
- 回傳整數檔案描述符(
int)。
- 若檔案未開啟或不支援(如
StringIO),拋出 IOError/UnsupportedOperation。
基本範例
f = open('foo.txt', 'w')
print("Name:", f.name)
fd = f.fileno()
print("File Descriptor:", fd) # 例如 3
f.close()
標準串流描述符
| 串流 | 檔案描述符 | Python 物件 |
| 標準輸入 | 0 | sys.stdin |
| 標準輸出 | 1 | sys.stdout |
| 標準錯誤 | 2 | sys.stderr |
進階應用場景
1. 使用 os.read/os.write 進行無緩衝 I/O
import os
fd = os.open('data.bin', os.O_RDWR | os.O_CREAT)
os.write(fd, b'hello')
os.lseek(fd, 0, os.SEEK_SET)
data = os.read(fd, 5)
print(data) # b'hello'
os.close(fd)
2. select 監控多檔案就緒狀態
import select
import sys
# 監控標準輸入是否可讀(5 秒逾時)
rlist, _, _ = select.select([sys.stdin], [], [], 5)
if rlist:
line = sys.stdin.readline()
print("Input:", line.strip())
else:
print("Timeout")
3. mmap 記憶體映射大檔案
import mmap
with open('bigfile.dat', 'r+b') as f:
mm = mmap.mmap(f.fileno(), 0) # 映射整個檔案
print(mm[:10]) # 直接像 bytes 一樣切片讀取
mm[0:5] = b'HELLO' # 修改即寫回檔案
mm.close()
4. fcntl 檔案鎖定(Unix/Linux)
import fcntl
with open('lockfile', 'w') as f:
fcntl.flock(f.fileno(), fcntl.LOCK_EX) # 獨佔鎖
# 關鍵區段...
fcntl.flock(f.fileno(), fcntl.LOCK_UN) # 釋放
注意事項
- 檔案描述符是進程級資源,
fork() 子進程會繼承;close() 會釋放該整數供重用。
- Python 高層檔案物件(
TextIOWrapper、BufferedWriter)有自己的緩衝區,直接操作 fileno() 繞過緩衝區可能導致資料不一致,需先 flush()。
- Windows 上檔案描述符行為與 Unix 類似,但部分
fcntl/mmap 參數不同。
總結
fileno() 是通往作業系統底層 I/O 介面的橋樑。一般應用極少直接使用,但在高效能網路伺服器、記憶體映射大檔案、檔案鎖定、多工 I/O 多工等系統級開發中不可或缺。理解檔案描述符與 Python 檔案物件的關係,有助於排查 I/O 相關疑難雜症。
- 上一篇文章: Python 檔案操作:flush() 方法強制刷新緩衝區完整教學
- 下一篇文章: Python 檔案操作:isatty() 方法判斷是否為終端機裝置完整教學
Copyright ©
程式碼之家 All Rights Reserved