Python os.pwrite() - 将指定的字节串写入与指定的文件描述符

Python os.pwrite()

Python中的os.pwrite()方法用于将指定的字节串写入与指定的文件描述符相关联的文件中指定的位置。任何现有值将在指定位置被覆盖。

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

注意:os.pwrite()方法用于低级操作,应该应用于os.open()或os.pipe()方法返回的文件描述符。

语法:os.pwrite(fd, str, offset)

参数:

fd:表示要写入的文件的文件描述符。

一个字节串,表示要写入文件的内容

offset:表示起始位置的整数值。文件写入将从这个偏移值开始。

返回类型:该方法返回一个整数值,表示实际写入的字节数。

将下面的文本视为名为file.txt的文件的内容。

C, C++, Java, C#, PHP

示例1

使用os.pwrite()方法

# Python program to explain os.pwrite() method
  
# Importing os module
import os
  
# Filename
filename = "file.txt"
  
# Open the file and get the
# file descriptor associated 
# with it using os.open method
fd = os.open(filename, os.O_RDWR)
  
# String to be written in the file
s = "Python, "
  
# converting string to bytestring
text = s.encode("utf-8")
  
# Position from where
# file writing will start 
offset = 0
  
# As offset is 0, bytestring
# will be written in the 
# beginning of the file
  
# Write the bytestring
# to the file indicated by 
# file descriptor at 
# specified position
bytesWritten = os.pwrite(fd, text, offset)
print("Number of bytes actually written:", bytesWritten)
  
# Print the content of the file
with open(filename) as f:
    print(f.read())
  
# String to be written in the file
s = "Javascript, "
  
# converting string to bytestring
text = s.encode("utf-8")
  
# Position from where
# file writing will start 
# os.stat(fd).st_size will return
# file size in bytes
# so bytestring will be written 
# at the end of the file
offset = os.stat(fd).st_size
  
# Write the bytestring
# to the file indicated by 
# file descriptor at 
# specified position
bytesWritten = os.pwrite(fd, text, offset)
print("\nNumber of bytes actually written:", bytesWritten)
  
# Print the content of the file
with open(filename) as f:
    print(f.read())
  
# String to be written in the file
s = "R Programming, "
  
# converting string to bytestring
text = s.encode("utf-8")
  
# Position from where
# file writing will start
offset = 10
  
# Write the bytestring
# to the file indicated by 
# file descriptor at 
# specified position
bytesWritten = os.pwrite(fd, text, offset)
print("\nNumber of bytes actually written:", bytesWritten)
  
# Print the content of the file
with open(filename) as f:
    print(f.read())

输出:

Number of bytes actually written: 8
Python, Java, C#, PHP

Number of bytes actually written: 12
Python, Java, C#, PHP
Javascript, 

Number of bytes actually written: 15
Python, JaR Programming, ascript, 

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程