os.read() Method



Description

The method read() reads at most n bytes from file desciptor fd, return a string containing the bytes read. If the end of file referred to by fd has been reached, an empty string is returned.

Note − This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe(). To read a "file object" returned by the built-in function open() or by popen() or fdopen(), or sys.stdin, use its read() or readline() methods.

Syntax

Following is the syntax for read() method −

os.read(fd,n)

Parameters

  • fd − This is the file descriptor of the file.

  • n − These are n bytes from file descriptor fd.

Return Value

This method returns a string containing the bytes read.

Example

The following example shows the usage of read() method −

import os, sys

# Open a file
fd = os.open("foo.txt",os.O_RDWR)

# Reading text
ret = os.read(fd,12)
print (ret.decode())

# Close opened file
os.close(fd)
print ("Closed the file successfully!!")

Let us compile and run the above program, this will print the contents of file foo.txt −

This is test
Closed the file successfully!!
python_os_file_directory_methods.htm
Advertisements