Python | os.write () method

os.write() in Python is used to write a string of bytes to a given file descriptor.

File descriptor — it is a small integer value that corresponds to a file that was opened by the current process. It is used to perform various lower level I / O like read, write, send, etc.

Note os.write() is intended for low-level operations and should be applied to the file descriptor returned by os. open () or os.pipe() .

Syntax: os.write (fd, str)

fd : The file descriptor representing the target file.
str : A bytes-like object to be written in the file.

Return Type: This method returns an integer value which represents the number of bytes actually written.

Code : using the os.write () method to write a byte string to the given file descriptor.

# Python program to explain the method os.write ( )

# import of the os module < / code>

import os

# File path

path = "/ home / ihritik / Documents / GeeksForGeeks.txt"


# Open the file and get
# file descriptor associated
# using os.open () method

fd = os. open (path, os.O_RDWR)


# Line to write

s "GeeksForGeeks: A Computer science portal for Geeks."

# Convert string to bytes

line = str . encode (s)

# Write line to file
# associated with file
# handle fd and get the number
# Bytes actually written

numBytes = os.write (fd, line)


print ( " Number of bytes written: " , numBytes)

# close the file descriptor
os.close (fd)


 Number of bytes written: 51                                        
Get Solution for free from DataCamp guru