📜  Python| os.pwrite() 方法

📅  最后修改于: 2022-05-13 01:54:32.481000             🧑  作者: Mango

Python| os.pwrite() 方法

Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。

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

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

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

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

C, C++, Java, C#, PHP
代码:使用 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,