当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python os.pread()用法及代码示例


Python中的OS模块提供了与操作系统进行交互的函数。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的函数的便携式方法。

os.pread()Python中的方法用于在给定偏移值的位置从与给定文件描述符关联的文件中读取最多n个字节。

如果在从给定文件描述符读取字节时到达文件末尾,os.pread()方法将为所有要读取的剩余字节返回一个空字节对象,并且它不影响文件偏移值。


文件描述符是一个小整数值,对应于当前进程已打开的文件。它用于执行各种较低级别的I /O操作,例如读取,写入,发送等。

注意os.pread()方法旨在用于低级操作,并且应应用于由返回的文件描述符os.open()或者os.pipe()方法。

用法: os.pread(fd, n, offset) 

参数:
fd:表示要读取文件的文件描述符。
n:一个整数值,表示要从与给定文件描述符fd相关的文件中读取的字节数。
offset:表示偏移字节的整数值。

返回类型:此方法返回一个字节字符串,该字符串表示在给定偏移值的位置从与文件描述符fd相关联的文件读取的字节。

将以下文本视为名为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.

代码:os.pread()方法的使用
# 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'


相关用法


注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 Python | os.pread() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。