Python的read()
方法從檔描述符fd
讀取最多n
個位元組,返回一個包含讀取位元組的字串。 如果fd
引用的檔結尾已經到達,則返回一個空字元串。
注意 - 此功能適用於低級
I/O
,並且必須應用於os.open()
或pipe()
返回的檔描述符。要讀取內置函數open()
,popen()
,fdopen()
或sys.stdin
返回的“檔對象”,請使用其read()
或readline()
方法。
語法
以下是read()
方法的語法 -
os.read(fd,n)
參數
- fd - 這是檔的檔描述符。
- n - 這些是檔描述符
fd
的n
個位元組。
返回值
- 此方法返回一個包含讀取位元組的字串。
示例
以下示例顯示了read()
方法的用法。
# !/usr/bin/python3
import os, sys
# Open a file
fd = os.open("foo.txt",os.O_RDWR)
# Reading text
ret = os.read(fd,12)
print (ret.decode())
# Close opened file
os.close(fd)
print ("Closed the file successfully!!")
編譯並運行上面的程式,這樣就列印檔foo.txt
的內容 -
This is test
Closed the file successfully!!
上一篇:
Python os模組方法
下一篇:
Python異常處理