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
广告