當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python os.pwrite()用法及代碼示例


Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。

os.pwrite()Python中的方法用於將指定的字節字符串寫入與指定位置的指定文件描述符關聯的文件。任何現有值都將在指定位置被覆蓋。

文件描述符是一個小整數值,對應於當前進程已打開的文件。它用於執行各種較低級別的I /O操作,例如讀取,寫入,發送等。


注意os.pwrite()方法旨在用於低級操作,並且應應用於由返回的文件描述符os.open()或者os.pipe()方法。

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

參數:
fd:表示要寫入文件的文件描述符。
str:一個字節字符串,表示要寫入文件的內容
offset:表示起始位置的整數。文件寫入將從該偏移值開始。

返回類型:此方法返回一個整數值,表示實際寫入的字節數。 。

將以下文本視為名為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, 


相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.pwrite() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。