The Fdopen() Function Of Os Module In Python


  • Based on the type of I/O selected, the function fdopen() instantiates one of the IOBase derived classes and returns the object. For example, when text I/O is selected the function returns an instance of TextIOWrapper. If binary I/O is selected the function returns an instance of FileIO.

  • The behaviour is the same as that of the built-in function open(). While the built-in function open() creates and returns the the required file object using a file path, the function fdopen() constructs the file object using a file descriptor.

  • A file descriptor can be created using functions like


# Example Python program that creates a
# file object using the function os.fd_open(),
# similar to the one returned by the
# built-in function open()
import os

# Open a file and get the file descriptor
fd         ="./Rain.txt", os.O_RDWR | os.O_SYNC | os.O_APPEND, 0o744)

# Create a file object from the file descriptor
file     = os.fdopen(fd, "a")

# Append text
file.write("\nAnother day;")

# Read the contents back and print
fd         ="./Rain.txt", os.O_RDONLY, 0o744)
file     = os.fdopen(fd, "r")

# Read and print the file contents
ln = file.readline()
while ln:
    ln = file.readline()


Rain, Rain,

Go away;

Come again,

Another day;


Copyright 2023 ©