Python的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!!
上一篇:
Python os模块方法
下一篇:
Python异常处理