Easy Tutorial
❮ Python Namespace Scope Ref Set Difference_Update ❯

Python3 os.write() Method

Python3 OS File/Directory Methods


Overview

The os.write() method is used to write a string to a file descriptor fd. It returns the actual length of the string written.

Valid in Unix.

Syntax

The syntax for the write() method is as follows:

os.write(fd, str)

Parameters

-

fd -- The file descriptor.

-

str -- The string to be written.

Return Value

This method returns the actual number of bytes written.

Example

The following example demonstrates the use of the write() method:

#!/usr/bin/python3

import os, sys

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

# Write a string
str = "This is tutorialpro.org site"
ret = os.write(fd, bytes(str, 'UTF-8'))

# Print the return value
print("Number of bytes written: ")
print(ret)

print("Write successful")

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

Executing the above program outputs the following:

Number of bytes written: 
23
Write successful
File closed successfully!!

Python3 OS File/Directory Methods

❮ Python Namespace Scope Ref Set Difference_Update ❯