Python fileno method:

The fileno is a method of IOBase class in Python that returns the underlying file descriptor of the stream. In other words, it returns an integer file number to request I/O operations from the operating system.

If we open the file in a read mode, the file must be present in the current directory. But, if we open it in a write mode, it will create a new file and return its file descriptor. Therefore, in the absence of a file or if the file is closed, it will raise an exception.

Signature

The signature for the fileno method is as shown below.

fileObject.fileno()

Parameters and return type

  • Here, The fileno method doesn’t take any parameters.
  • However, it returns an integer file descriptor.

Python fileno method Examples:

Example 1: We will open a file in write mode and print its descriptor in this example.

# Open a file
f1 = open("test.txt", "w")
print ("File Name ", f1.name)

fd1 = f1.fileno()
print ("File Descriptor ", fd1)

# Closing file
f1.close()

Output

File Name  test.txt
File Descriptor  3

Example 2: In this example, we will open a file in reading mode and assume that the file exists in the current directory.

# Open a file
f1 = open("test.txt", "r")
print ("File Name ", f1.name)

fd1 = f1.fileno()
print ("File Descriptor ", fd1)

# Closing file
f1.close()

Output

File Name  test.txt
File Descriptor  3

Example 3: In this example, we will access the file descriptor after closing a file that will raise an exception.

#Initializing 
# Open a file
f1 = open("test.txt", "w")
print ("File Name ", f1.name)

fd1 = f1.fileno()
print ("File Descriptor ", fd1)

# Closing file
f1.close()

#Accessing File Descriptor again
fd1 = f1.fileno()

Output

File Name  test.txt
File Descriptor  3
Traceback (most recent call last):
  File "main.py", line 12, in 
    fd1 = f1.fileno()
ValueError: I/O operation on closed file

References

Happy Learning 🙂

Leave A Comment