Python的read()
方法從檔案描述符fd
讀取最多n
個位元組,返回一個包含讀取位元組的字串。 如果fd
參照的檔案結尾已經到達,則返回一個空字串。
注意 - 此功能適用於低階
I/O
,並且必須應用於os.open()
或pipe()
返回的檔案描述符。要讀取內建函式open()
,popen()
,fdopen()
或sys.stdin
返回的「檔案物件」,請使用其read()
或readline()
方法。
語法
以下是read()
方法的語法 -
os.read(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!!