Python| os.pread() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
Python中的os.pread()
方法用于在给定偏移值的位置从与给定文件描述符关联的文件中读取最多n个字节。
如果在从给定文件描述符中读取字节时已到达文件末尾,则os.pread()
方法将为所有要读取的字节返回一个空字节对象,并且它不会影响文件偏移值。
文件描述符是与当前进程已打开的文件相对应的小整数值。它用于执行各种较低级别的 I/O 操作,如读、写、发送等。
注意: os.pread()
方法用于低级操作,应应用于os.open()
或os.pipe()
方法返回的文件描述符。
Syntax: os.pread(fd, n, offset)
Parameters:
fd: A file descriptor representing the file to be read.
n: An integer value denoting the number of bytes to be read from the file associated with the given file descriptor fd.
offset: An integer value denoting the offset bytes.
Return Type: This method returns a bytestring which represents the bytes read from the file associated with the file descriptor fd at a position of given offset value.
将以下文本视为名为Python_intro.txt的文件的内容。
Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently.
# Python program to explain os.pread() method
# importing os module
import os
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open("Python_intro.txt", os.O_RDONLY)
# Number of bytes to be read
n = 50
# Read at most n bytes from
# file descriptor fd
# using os.read() method
readBytes = os.read(fd, n)
# Print the bytes read
print(readBytes)
# Now set the Offset value
offset = 20
# Read at most n bytes from
# file descriptor fd at a position of
# given offset value using os.pread() method
readBytes = os.pread(fd, n, offset)
# Print the bytes read
print(readBytes)
# close the file descriptor
os.close(fd)
b'Python is a widely used general-purpose, high leve'
b'sed general-purpose, high level programming langua'