The fdopen() function of os module in Python

The fdopen() function of os module in Python creates a file object using an already existing file descriptor.

Os Updated 9 May 2023 1 min read

Overview

  • 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 os.open().

Example

python
# 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         = os.open("./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;")

            file.close()

# Read the contents back and print

            fd         = os.open("./Rain.txt", os.O_RDONLY, 0o744)

            file     = os.fdopen(fd, "r")

# Read and print the file contents

            ln = file.readline()

            while ln:

                print(ln)

                ln = file.readline()

            file.close()

Output

Output
Rain, Rain,

Go away;

Come again,

Another day;