The Python os.read() method is used to read a specified number of bytes from a file associated with the given file descriptor. And, returns a byte string containing the bytes read.
If end of file is reached while reading, it will return an empty bytes object.
SyntaxFollowing is the syntax for Python os.read() method −
os.read(fd, n)Parameters
The Python os.read() method accepts two parameters that are listed below −
fd − This is the file descriptor of the file.
n − This parameter indicates the number of bytes to read from the file.
The Python os.read() method returns a string containing the bytes read.
ExampleThe following example shows the usage of read() method. Here, we first get the size of file and then, read the text from it.
import os, sys # Open a file fd = os.open("newFile.txt", os.O_RDWR) #getting file size f_size = os.path.getsize("newFile.txt") # Reading text ret = os.read(fd, f_size) print("Reading text from file: ") print (ret) # Close opened file os.close(fd) print ("file closed successfully!!")
Let us compile and run the above program, this will print the contents of file "newFile.txt" −
Reading text from file... b'This is tutorialspoint' file closed successfully!!Example
In the below example, we read the first 10 characters from the given file using read() method.
import os, sys # Open a file fd = os.open("newFile.txt", os.O_RDWR) # Reading text ret = os.read(fd, 10) print("Reading text from file: ") print (ret) # Close opened file os.close(fd) print ("file closed successfully!!")
On running the above program, it will print the first 10 characters of file "newFile.txt" −
Reading text from file: b'This is tu' file closed successfully!!
os_file_methods.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4