os.read() 方法



描述

read() 方法最多從檔案描述符 fd 中讀取 n 個位元組,返回包含讀取的位元組的字串。如果已到達 fd 所引用的檔案的末尾,則返回空字串。

注意 - 此函式用於低階 I/O,並且必須應用於 os.open() 或管道返回的檔案描述符。要讀取由內建函式 open() 或 popen() 或 fdopen() 或 sys.stdin 返回的“檔案物件”,請使用其 read() 或 readline() 方法。

語法

以下是 read() 方法的語法 -

os.read(fd,n)

引數

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

  • n - 這是檔案描述符 fd 中的 n 個位元組。

返回值

此方法返回包含讀取的位元組的字串。

示例

以下示例顯示了 read() 方法的使用 -

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_file_directory_methods.htm
廣告