Python 3 – File fileno() Method
In Python, the fileno()
method is used to get the file descriptor associated with the file object. A file descriptor is an integer value that uniquely identifies an open file within a process. The fileno()
method is only applicable to file objects that are associated with a real file. This method returns the file descriptor associated with the file object.
Syntax
file_object.fileno()
Parameters
The fileno()
method does not take any parameters.
Return Value
The fileno()
method returns an integer value that represents the file descriptor associated with the file object.
Example
In this example, we’ll create a file and print the file descriptor using the fileno()
method.
file = open("test.txt", "w")
print("File descriptor:", file.fileno())
Output:
File descriptor: 3
Note: The output may vary depending on the system.
In this example, we have created a file named test.txt
in write mode using the open()
function. Then we print the file descriptor associated with the file object using the fileno()
method.
Example
In this example, we’ll read from a file and use the fileno()
method to get the file descriptor.
file = open("test.txt", "r")
print("File descriptor:", file.fileno())
file.close()
Output:
File descriptor: 3
Note: The output may vary depending on the system.
First, we have opened the test.txt
file in read mode using the open()
function. Then we print the file descriptor associated with the file object using the fileno()
method. Finally, we close the file using the close()
method.
Example
In this example, we’ll use the os.dup()
method to duplicate the file descriptor and use it to write to the file.
import os
file = open("test.txt", "w")
print("File descriptor:", file.fileno())
fd = os.dup(file.fileno())
os.write(fd, b"Hello, World!\n")
file.close()
Output:
File descriptor: 3
Note: The output may vary depending on the system.
In this example, we have opened the test.txt
file in write mode using the open()
function. Then we print the file descriptor associated with the file object using the fileno()
method. We use the os.dup()
method to duplicate the file descriptor and assign it to the fd
variable. Finally, we write the string “Hello, World!\n” to the file using the os.write()
method and close the file using the close()
method.
Conclusion
In conclusion, the fileno()
method is used to get the file descriptor associated with the file object in Python. It returns an integer value that represents the file descriptor. This method is only applicable to file objects that are associated with a real file. In this article, we saw examples of how to use the fileno()
method to get the file descriptor and how to duplicate it using the os.dup()
method.