Read() Function Of Os Module In Python

Overview:

  • Given a file descriptor, the os.read() function reads the specified number of bytes or less based on the unread/available number of bytes from the file.

  • A bytes object of zero length is returned once all the bytes are read(i.e., the end of file is reached).

  • When a file is opened through the Python built-in function open(), the read() function of the file object is to be used for reading the file contents. The os.read() is a low-level I/O function that reads raw bytes of a file using a file descriptor.

 

Parameters:

fd – The file descriptor obtained through os.open() function

n – Number of bytes to be read

 

Return Value:

A bytes object.

Example:

# Example Python program that reads from
# a file and print the file contents
# using the function os.read()
import os

# Open a file in read only mode
fpath    = "/PythonProgs/Wheels.txt"
fmode    = 0o744
oFlags    = os.O_RDONLY

# Read from the file and print the raw bytes
fdesc     = os.open(fpath, os.O_RDWR, mode = fmode)

oneGo      = 8
bytesRead = os.read(fdesc, oneGo)
print(type(bytesRead))

while bytesRead:
    print(bytesRead)
    bytesRead = os.read(fdesc, oneGo)

# Close the file (descriptor)
os.close(fdesc)

Output:

<class 'bytes'>
b'The whee'
b'ls on th'
b'e bus go'
b' round a'
b'nd round'

 


Copyright 2023 © pythontic.com