os.write() Method



Description

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

Syntax

Following is the syntax for write() method −

os.write(fd, str)

Parameters

  • 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.

Example

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

import os, sys

# Open a file
fd = os.open( "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!!
python_os_file_directory_methods.htm
Advertisements