Python3 os.read()方法

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!!

上一篇: Python3檔方法 下一篇: Python3 os檔目錄的方法