Python | os.pwrite() method
Last Updated :
07 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.pwrite()
method in Python is used to write the specified bytestring to the file associated with the specified file descriptor at the specified position. Any existing value will be overwritten at the specified position.
A file descriptor is small integer value that corresponds to a file that has been opened by the current process. It is used to perform various lower level I/O operations like read, write, send etc.
Note: os.pwrite()
method is intended for low-level operation and should be applied to a file descriptor as returned by os.open()
or os.pipe()
method.
Syntax: os.pwrite(fd, str, offset)
Parameters:
fd: A file descriptor representing the file to be written.
str: A bytestring representing the content to be written in the file
offset: An integer value denoting the starting position. File writing will start from this offset value.
Return Type: This method returns an integer value representing the number of bytes actually written. .
Consider the below text as the content of the file named file.txt.
C, C++, Java, C#, PHP
Code: Use of os.pwrite() method
import os
filename = "file.txt"
fd = os. open (filename, os.O_RDWR)
s = "Python, "
text = s.encode( "utf-8" )
offset = 0
bytesWritten = os.pwrite(fd, text, offset)
print ( "Number of bytes actually written:" , bytesWritten)
with open (filename) as f:
print (f.read())
s = "Javascript, "
text = s.encode( "utf-8" )
offset = os.stat(fd).st_size
bytesWritten = os.pwrite(fd, text, offset)
print ( "\nNumber of bytes actually written:" , bytesWritten)
with open (filename) as f:
print (f.read())
s = "R Programming, "
text = s.encode( "utf-8" )
offset = 10
bytesWritten = os.pwrite(fd, text, offset)
print ( "\nNumber of bytes actually written:" , bytesWritten)
with open (filename) as f:
print (f.read())
|
Output:
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,
Share your thoughts in the comments
Please Login to comment...