open() function of os module in Python

The os.open() function opens a file, based on on the flags and modes parameters passed to it and returns a file descriptor. The descriptor can be used for performing low level I/O using function like os.read() and os.write().

Os Updated 1 May 2023 1 min read

Overview

  • The os.open() implements the Unix function open(). This is a low-level function that accepts Unix file creation modes and file permissions as parameters to create a file descriptor from a given file path.
  • The Python built-in function open() dynamically creates and returns different types of objects based on the chosen I/O mode (text or raw), which is generally suitable for most of the common needs of file I/O.The file descriptor returned by os.open() can be used to perform I/O involving raw bytes or can be used to develop objects and functions to support specialised I/O (e.g., involving text).

Parameters

path - File path

flags - Flags that are ORed together to specify read, write, create and other similar modes

mode - Octal literal specifying file permissions. The effective mode is given by (mode and (not mask value))

Example

python
# Example Python program that uses low level function os.open()

            # to create a file and perform I/O operations on it

            import os

# Open a file on a given path

            fpath  = "/PythonProgs/filetest.txt"

            flgs   = os.O_RDWR | os.O_CREAT

            fd     = os.open(fpath, flgs, mode = 0o744)

# Write bytes to the file using the file descriptor

            numBytes = os.write(fd, "hello world".encode())

            print("Number of bytes written:%d"%numBytes)

            os.close(fd)

# Read and print raw bytes

            fd     = os.open(fpath, os.O_RDWR, mode = 0o744)

            bytesRead = os.read(fd, 8)

            print(type(bytesRead))

while bytesRead:

                print(bytesRead)

                bytesRead = os.read(fd, 8)

os.close(fd)

Output

Output
Number of bytes written:11

            <class 'bytes'>

            b'hello wo'

            b'rld'