Everything is considered as a file in Linux. For example, files, directories, and sockets are all files.
Every file has a non-negative integer associated with it. This non-negative integer is called the file descriptor for that particular file. The file descriptors are allocated in sequential order with the lowest possible unallocated positive integer value taking precedence.
Whenever a program is run or executed, the following files are always opened:
STDIN
) with the file descriptor as 0
.STDOUT
) with the file descriptor as 1
.STDERR
) with the file descriptor as 2
.os
moduleThe os
library in Python provides functions that help us interact with the underlying operating system.
close
method of the os
moduleThe close
method of the os
module is used to close the given file descriptor.
Note: Refer here to read more about how to close a range of file descriptors.
os.close(fd)
fd
is the file descriptor that needs to be closed.
Let’s look at the code below:
import osf_name = "file.txt"fileObject = open(f_name, "r")fd = fileObject.fileno()print("The file descriptor for %s is %s" % (f_name, fd))os.close(fd)
In the code above, we create a file called file.txt
.
os
module.f_name
that holds the file name.open()
with the read mode (r
).fileno()
method.os.close()
method.