Trusted answers to developer questions

How to get the file descriptor for a given file in Python

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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

main.py
file.txt
import socket
f_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 socket package.
  • Line 3: We define a variable called f_name that 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 fileno method to obtain the file descriptor for the file object.
  • Line 8: We use the socket() method to create a TCP socket called sock.
  • Line 9: We use the fileno method to obtain the file descriptor for the sock object obtained in Line 8.

Note: Refer to Socket programming in Python to learn more socket programming in Python.

RELATED TAGS

python
Did you find this helpful?