The write function of os module in Python

Function:

os.write(fd, str, /)

Overview:

  • The write() function writes a given collection of bytes in the str parameter to the file represented by the file descriptor fd.
  • The return value of the built-in function open() is a file object of type from any of the several I/O wrappers based on the chosen I/O type. e.g., a TextIOWrapper object in case of text I/O, a FileIO object in case of binary I/O without buffering. The write() method on these objects to be called when a file object is obtained through the built-in function open(). The os.write() is to be used when a file descriptor is used to perform low level I/O, typically opened through the os.open().

Return Value:

Number of bytes written to the file.

Example:

# Example Python program that uses the low-level I/O
# function os.write() to write raw bytes into a file
import os

fPath    = "/PythonProgs/OneTwoBuckle.txt"
fFlags     =  os.O_RDWR | os.O_CREAT

song = """One, two, buckle my shoe
Three, four, shut the door
Five, six, pick up sticks
Seven, eight, lay them straight
Nine, ten, begin again"""

fd         = os.open(fPath, fFlags, 0o744)
count     = os.write(fd, song.encode())
print("Written %d bytes to %s"%(count, fPath))

Output:

Written 132 bytes to /PythonProgs/OneTwoBuckle.txt

 


Copyright 2024 © pythontic.com