Python os.fdopen() Method

Musfirah Waseem Jan 30, 2023
  1. Syntax of Python os.fdopen() Method
  2. Example 1: Use the os.fdopen() Method in Python
  3. Example 2: Read the File After Using the os.fdopen() Method
  4. Example 3: Use the os.fdopen Method With the os.open() Method
Python os.fdopen() Method

Python os.fdopen() method returns an open file object connected to the fd file descriptor. It is an alias of the os.open() method.

Both methods don’t have a difference in their working except that the os.fdopen() method’s first argument should be an integer.

Syntax of Python os.fdopen() Method

os.fdopen(fd, mode)

Parameters

fd It is a file descriptor for which a file object is needed to open.
mode It is an optional parameter representing the mode of the newly opened file. The default value of the mode is an octal numeric integer 0o777.
The most used values of the mode parameter are r for reading a file, w for writing/truncating a file, and a for appending the file.

Return

This method returns the newly opened file’s path connected to the file descriptor.

Example 1: Use the os.fdopen() Method in Python

import os

import sys

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

file = os.fdopen(fd, "w+")

file.write("Hello, World!")

file.close()

print("File created successfully.")

Output:

File created successfully.

While using the os.fdopen() method, we can use one or more modes simultaneously by using the vertical bar |.

Example 2: Read the File After Using the os.fdopen() Method

import os

path_address = "./File.txt"

mode_set = 0o666

flags = os.O_CREAT | os.O_RDWR

descriptor = os.open(path_address, flags, mode_set)

file = os.fdopen(descriptor, "w+")

print("The new file has been created.")

line = "Hello, World! Programming is fun!"

os.write(descriptor, line.encode())

print("The text has been successfully entered into the file.")

file.close()

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

Output:

The new file has been created.
The text has been successfully entered into the file.
The file descriptor has been closed successfully.

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