Python os.write() Method

Python os.write() Method

  1. Syntax of os.write() Method
  2. Example 1: Use os.write() Method to Write a Byte-String to a Given File Descriptor
  3. Example 2: Alternative Syntax of the os.write() Method
  4. Example 3: Use the os.fdopen Method With the os.write() Method

Python os.write() method is an efficient way of writing a byte of string to a specific file descriptor.

Syntax of os.write() Method

os.write(fd, string)

Parameters

fd It is an optional parameter representing a file descriptor referring to a path.
string It is any byte of strings that needs to be written in the file.

Return

The return type of this method is an integer value representing the number of bytes written successfully on a file.

Example 1: Use os.write() Method to Write a Byte-String to a Given File Descriptor

import os

fd = os.open( "File.txt", os.O_RDWR|os.O_CREAT )

bytes=os.write(fd, 'Hello, World!'.encode())

os.close( fd )

print("The number of bytes written is:", bytes)

print ("The file has been closed successfully!")

Output:

The number of bytes written is: 13
The file has been closed successfully!

The methods os.open() and os.write() go hand in hand because one has to open a file and write data. Data can’t be written into a file in another way.

Example 2: Alternative Syntax of the os.write() Method

import os

file = open("File.txt", "w")

file.write("Hello, World!")

file.close()

file = open("File.txt", "r")

print(file.read())

Output:

Hello, World!

It is a healthy practice for any programmer to close all the newly opened files using the os.close() method.

Example 3: Use the os.fdopen Method With the os.write() Method

import os

with os.fdopen(os.open("File.txt",os.O_CREAT | os.O_RDWR ),'w') as fd:
    fd.write("Hello, World!")

print ("The file descriptor has been closed successfully.")

Output:

The file descriptor has been closed successfully.

Note that the returned file descriptor from this method is non-inheritable.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method