How to get the file descriptor for a given file in Python
What are file descriptors in Linux?
Files, directories, sockets, and so on, are all files in Linux. Every file has a non-negative integer associated with it. This non-negative integer is called the file descriptor for that particular file. File descriptors are allocated in sequential order, with the lowest possible unallocated positive integer value taking precedence.
The following file descriptors are always opened whenever a program is run/executed.
- Standard Input (STDIN) is the default reading descriptor with a value of
0. - Standard Output (STDOUT) is the default writing descriptor with a value of
1. - Standard Error (STDERR) is the default error descriptor with a value of
2.
The fileno method
In Python, fileno is an instance method on the file object that returns the file descriptor for the given file.
Syntax
fileObject.fileno()
Parameters
This method has no parameters.
Return Value
This method returns the file descriptor of the particular fileobject.
Code
import socketf_name = "file.txt"fileObject = open(f_name, "r")print("The file descriptor for %s is %s" % (f_name, fileObject.fileno()))sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)print("The file descriptor for TCP socket is %s" % (sock.fileno()))
Explanation
In the code above, we create a file called file.txt.
- Line 1: we import the
socketpackage. - Line 3: We define a variable called
f_namethat holds the file name. - Line 4: We create a file object for reading by using the
open()with the read mode (r). - Line 6: We use the
filenomethod to obtain the file descriptor for the file object. - Line 8: We use the
socket()method to create a TCP socket calledsock. - Line 9: We use the
filenomethod to obtain the file descriptor for thesockobject obtained in Line 8.
Note: Refer to Socket programming in Python to learn more socket programming in Python.