Open() function of os module in Python

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:

# 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:

Number of bytes written:11
<class 'bytes'>
b'hello wo'
b'rld'

 


Copyright 2024 © pythontic.com