Python os.read()方法

2019-10-16 23:04:57

Python的read()方法從檔案描述符fd讀取最多n個位元組,返回一個包含讀取位元組的字串。 如果fd參照的檔案結尾已經到達,則返回一個空字串。

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

語法

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

os.read(fd,n)

引數

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

返回值

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

範例

以下範例顯示了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!!