Python File fileno() Method

The descriptor of the file is a low-level identifier that is utilized by the operating system to access a file or a device. To get/retrieve the file descriptor in integer format, the built-in “fileno()” method is utilized in Python. This write-up will provide you with a thorough guide on the “fileno()” method with appropriate examples via the below contents:


What is the Python File “fileno()” Method?

The integer file descriptor of a stream, which is a numeric value that links an open file with the operating system, can be obtained by using the “fileno()” method in Python. An open file is associated with a numeric value, called a file descriptor, that the operating system uses to refer to the file.

Note: When the file descriptor is not used by the operator system, then the program raises an error.





No parameters

Return Value

The “fileObject.fileno()” method retrieves the integer file descriptor.

Example 1: Retrieve the Integer File Descriptor

In this example, first, we open the file in read mode and then we retrieve the integer file descriptor by using the “file.fileno()” method.

file = open("example.txt", "r")


The below output shows the file descriptor of the input file:

Example 2: Creating and Printing the File Descriptor

We can also create a new file and print their descriptor using the “file.fileno()” method. In the code below, the “open()” function is used multiple times to open/launch the file in write/writing mode. Next, the “file.fileno()” method is used to print the file descriptor. Finally, the file is closed/terminated utilizing the “file.fileno()” method:

file1 = open("new1.txt", "w")
file2 = open("new2.txt", "w")
print("file1.fileno(): ", file1.fileno())
print("file2.fileno(): ", file2.fileno())


The below output shows the file descriptor of the multiple input-created files:

Example 3: Retrieve the Integer File Descriptor After Closing the File

We can not retrieve the integer file descriptor after closing the file. Take the following code to demonstrate this example:

file1 = open("new1.txt", "w")


The following output shows the ValueError:


The “fileno()” method determines the integer of the stream file descriptor. If the operating system does not have a file descriptor for the file, the function will retrieve an error code. We can also create and print the file descriptor of the file using the “fileno()” method. However, once we close the file in Python, the file descriptor becomes inaccessible. This tutorial delivered a comprehensive guide on Python’s “file.fileno()” method using numerous examples.

About the author

Haroon Javed

Hi, I'm Haroon. I am an electronics engineer and a technical content writer. I am a tech geek who loves to help people to the best of my knowledge.