Python 3 - os.write() Method


The method write() writes the string str to file descriptor fd. Return the number of bytes actually written.


Following is the syntax for write() method −

os.write(fd, str)


  • fd − This is the file descriptor.

  • str − This is the string to be written.

Return Value

This method returns the number of bytes actually written.


The following example shows the usage of write() method.

# !/usr/bin/python3
import os, sys

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

# Write one string
line = "this is test" 

# string needs to be converted byte object
b = str.encode(line)
ret = os.write(fd, b)

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

# Close opened file
os.close( fd)

print ("Closed the file successfully!!")


When we run the above program, it produces the following result −

the number of bytes written: 12
Closed the file successfully!!