Python os.read() 方法



Python 的 os.read() 方法用於從與給定檔案描述符關聯的檔案中讀取指定數量的位元組。並返回包含已讀取位元組的位元組字串。

如果在讀取時到達檔案結尾,它將返回一個空的位元組物件。

語法

以下是 Python os.read() 方法的語法:

os.read(fd, n)

引數

Python os.read() 方法接受兩個引數,如下所示:

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

  • n − 此引數指示要從檔案中讀取的位元組數。

返回值

Python os.read() 方法返回一個包含已讀取位元組的字串。

示例

以下示例顯示了 read() 方法的使用。在這裡,我們首先獲取檔案的大小,然後從中讀取文字。

import os, sys

# Open a file
fd = os.open("newFile.txt", os.O_RDWR)

#getting file size
f_size = os.path.getsize("newFile.txt")	

# Reading text
ret = os.read(fd, f_size)
print("Reading text from file: ")
print (ret)

# Close opened file
os.close(fd)
print ("file closed successfully!!")

讓我們編譯並執行上述程式,這將列印檔案“newFile.txt”的內容:

Reading text from file...
b'This is tutorialspoint'
file closed successfully!!

示例

在下面的示例中,我們使用 read() 方法從給定檔案中讀取前 10 個字元。

import os, sys

# Open a file
fd = os.open("newFile.txt", os.O_RDWR)

# Reading text
ret = os.read(fd, 10)
print("Reading text from file: ")
print (ret)

# Close opened file
os.close(fd)
print ("file closed successfully!!")

執行上述程式後,它將列印檔案“newFile.txt”的前 10 個字元:

Reading text from file: 
b'This is tu'
file closed successfully!!
os_file_methods.htm
廣告