Python OS file/directory os.write() method

Python OS File/Directory os.write() Method

Description

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

Syntax

Following is the syntax of the write() method:

os.write(fd, str)

Parameters

  • fd – This is the file descriptor.
  • str – This is the string to be written.

Return Value

The 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 to a byte object
b=str.encode(line)
ret=os.write(fd, b)

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

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

When we run the above program, it produces the following output:

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

Leave a Reply

Your email address will not be published. Required fields are marked *