Python File fileno() Method



The Python File fileno() method returns the file descriptor (or file handle) of an open file. A file descriptor is an unsigned integer that is used by the operating system to identify the open files in an os kernel. It only holds non-negative values.

The file descriptor acts just like the ID that is used to acquire a record stored in a database. Therefore, Python uses it to perform various operations on the files; like opening a file, writing into a file, reading from a file or closing a file etc.

Syntax

Following is the syntax for the Python File fileno() method −

fileObject.fileno(); 

Parameters

The method does not accept any parameters.

Return Value

This method returns the integer file descriptor.

Example

The following example shows the usage of the Python File fileno() method. Here, we are trying to open a file "foo.txt" in the writing binary(wb) mode using a file object. Then, the fileno() method is called on this file object to retrieve the file descriptor referring to the current file.

# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)

fid = fo.fileno()
print("File Descriptor: ", fid)

# Close opened file
fo.close()

When we run above program, it produces following result −

Name of the file:  foo.txt
File Descriptor:  3

Example

The file descriptor is also used to close the file it represents.

In this example, we are importing the os module since a file descriptor is usually maintained by the operating system. Since we use file objects to refer a file, the fileno() method is called on a file object representing the current file to retrieve its file descriptor. The file is closed by passing the retrieved file descriptor as an argument to the os.close() method.

import os
# Open a file using a file object 'fo'
fo = open("hi.txt", "w")

fid = fo.fileno()
print("The file descriptor of the given file: ", str(fid))

# Close the opened file
os.close(fid)

If we compile and run the program above, the result is produced as follows −

The file descriptor of the given file:  3

Example

But if the file does not exist and the program still tries to open it in read mode, the fileno() method raises a FileNotFoundError.

fo = open("hi.txt", "r")

# Return the file descriptor
fid = fo.fileno()

# Display the file descriptor
print(fid)

#Close the opened file
fo.close()

Compile and run the program above, the output is obtained as follows −

Traceback (most recent call last):
  File "D:\Tutorialspoint\Programs\Python File Programs\filenodemo.py", line 1, in 
    fo = open("hi.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'hi.txt'
python_file_methods.htm
Advertisements