Python os.write() Method



The Python write() method of OS module is used for writing strings in the form of bytes. Return the number of bytes written.

This method writes the byte string to a given file descriptor returned by either "os.open()" or "os.pipe()" methods. Whether we can write or not to a file, it depends on the mode it is opened.

Syntax

The syntax for Python os.write() method is as follows −

os.write(fd, str)

Parameters

The Python os.write() method accepts the following parameters −

  • fd − This is the file descriptor which represents target file.

  • str − This parameter specifies the string to be written.

Return Value

The Python os.write() method returns the number of bytes written.

Example

The following example shows the usage of Python os.write() method. Here, we are opening a file in read-write mode and checking the number of bytes written.

import os, sys

# Open file
fd = os.open("f1.txt",os.O_RDWR|os.O_CREAT)

# Writing text
ret = os.write(fd, b"Writing a demo text...")

# ret consists of number of bytes written to f1.txt
print ("the number of bytes written: ")
print (ret)

print ("written successfully")

# Close opened file
os.close(fd)
print ("file closed successfully!!")

When we run above program, it produces following result −

the number of bytes written: 
22
written successfully
file closed successfully!!
python_files_io.htm
Advertisements