Python File fileno() Method – Tutorial with Examples

Python File fileno() Method

The fileno() method in Python returns the integer file descriptor that is associated with the file object. This method is used to get the file descriptor number for a file object that is opened with the open() function.

Syntax

file.fileno()

Return Value

The fileno() method returns an integer that represents the file descriptor number of the file object.

Examples

Example 1: Get file descriptor of an open file

In this example, we will create a file, open it using the open() function, and then get the file descriptor number of the file object using the fileno() method.

file = open("example.txt", "w")
print("File descriptor:", file.fileno())
file.close()

The output of the program:

File descriptor: 3

Example 2: Using fileno() method with standard input and output streams

The fileno() method can also be used with the standard input and output streams in Python. In this example, we will get the file descriptor number of the standard output stream.

import sys
print("File descriptor:", sys.stdout.fileno())

The output of the program:

File descriptor: 1

Example 3: Using fileno() method with sockets

The fileno() method can also be used with sockets in Python. In this example, we will create a TCP/IP socket and get the file descriptor number associated with the socket.

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 8000))
s.listen()

print("File descriptor:", s.fileno())

The output of the program:

File descriptor: 3

Use Cases

The fileno() method can be useful in situations where we need to work with low-level operating system functions that require file descriptors. For example, we might want to use the file descriptor with the os.read() or os.write() functions to read or write data from a file. Additionally, the fileno() method can be used to determine whether two file objects represent the same underlying file, by comparing their file descriptor numbers.

Leave a Reply

Your email address will not be published. Required fields are marked *