Python OS file/directory os.read() method
Python OS File/Directory os.read() Method
Description
The read() method reads up to n bytes of data from file descriptor fd and returns a string containing the bytes read. If the end of the file pointed to by file descriptor fd has been reached, an empty string is returned.
Note − This function is used for low-level I/O and must be applied to a file descriptor returned by os.open() or pipe(). To read a “file object” returned by the built-in functions open(), popen(), or fdopen(), or sys.stdin, use its read() or readline() methods.
Syntax
os.read(fd,n)
Parameters
- fd − This is the file descriptor for the file.
-
n − These are the n bytes read from the file descriptor fd.
Return Value
This method returns a string containing the bytes read.
Example
The following example demonstrates the use of the 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 the opened file
os.close(fd)
print ("Closed the file successfully!!")
Let’s compile and execute the above program. This will print the contents of the file foo.txt –
This is test
Closed the file successfully!!