Home » Python

Python File fileno() Method with Example

Python File fileno() Method: Here, we are going to learn about the fileno() method, how to get the file descriptor as an integer in Python?
Submitted by IncludeHelp, on December 18, 2019

File fileno() Method

fileno() method is an inbuilt method in Python, it is used to get the file number i.e. the file descriptor as an integer of the stream. It may return an error if an operating system does not use a file descriptor of the file is closed.

Syntax:

    file_object.fileno()

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is <class 'int'>, it returns an integer values which is the file descriptor of the file.

Example 1:

# Python File fileno() Method with Example

# creating two files
myfile1 = open("hello1.txt", "w")
myfile2 = open("hello2.txt", "w")

# printing the file descriptors
print("files are in write mode...")
print("myfile1.fileno(): ", myfile1.fileno())
print("myfile2.fileno(): ", myfile2.fileno())

# closing the files
myfile1.close()
myfile2.close()

# opening file in Read modes
myfile1 = open("hello1.txt", "r")
myfile2 = open("hello2.txt", "r")

# printing the file descriptors
print("files are in read mode...")
print("myfile1.fileno(): ", myfile1.fileno())
print("myfile2.fileno(): ", myfile2.fileno())

# closing the files
myfile1.close()
myfile2.close()

Output

files are in write mode...
myfile1.fileno():  5
myfile2.fileno():  6
files are in read mode...
myfile1.fileno():  5
myfile2.fileno():  6

Example 2:

# Python File fileno() Method with Example

# creating a file
myfile1 = open("hello1.txt", "w")

# printing the file descriptor
print("myfile1.fileno(): ", myfile1.fileno())

# closing the files
myfile1.close()

# trying to print the file descriptor
# after closing the file
# error will be returned
# printing the file descriptor
print("myfile1.fileno(): ", myfile1.fileno())

Output

myfile1.fileno():  5
Traceback (most recent call last):  File "main.py", line 16, in <module>
    print("myfile1.fileno(): ", myfile1.fileno())
ValueError: I/O operation on closed file


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.