描述
方法read()最多讀n來自文件描述符的字節fd, 返回一個包含讀取字節的字符串。如果引用的文件結尾fd已到達,則返回一個空字符串。
注意− 此函數用於低級 I/O,必須應用於 os.open() 或 pipe() 返回的文件描述符。要讀取由 內置 函數 open() 或 popen() 或 fdopen() 或 sys.stdin 返回的 “file object”,請使用其 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!!
相關用法
- Python 3 os.readlink()用法及代碼示例
- Python 3 os.rename()用法及代碼示例
- Python 3 os.renames()用法及代碼示例
- Python 3 os.removedirs()用法及代碼示例
- Python 3 os.remove()用法及代碼示例
- Python 3 os.rmdir()用法及代碼示例
- Python 3 os.fstatvfs()用法及代碼示例
- Python 3 os.minor()用法及代碼示例
- Python 3 os.close()用法及代碼示例
- Python 3 os.unlink()用法及代碼示例
- Python 3 os.major()用法及代碼示例
- Python 3 os.fdopen()用法及代碼示例
- Python 3 os.fdatasync()用法及代碼示例
- Python 3 os.isatty()用法及代碼示例
- Python 3 os.walk()用法及代碼示例
- Python 3 os.makedirs()用法及代碼示例
- Python 3 os.utime()用法及代碼示例
- Python 3 os.tcgetpgrp()用法及代碼示例
- Python 3 os.statvfs()用法及代碼示例
- Python 3 os.lchown()用法及代碼示例
注:本文由純淨天空篩選整理自 Python 3 - os.read() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。