Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to close a file descriptor in Python



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:

  • Standard input (STDIN) with the file descriptor as 0.
  • Standard output (STDOUT) with the file descriptor as 1.
  • Standard error (STDERR) with the file descriptor as 2.

The os module

The os library in Python provides functions that help us interact with the underlying operating system.

The close method of the os module

The 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.



fd is the file descriptor that needs to be closed.

Code example

Let’s look at the code below:
import os

f_name = "file.txt"
fileObject = open(f_name, "r")
fd = fileObject.fileno()
print("The file descriptor for %s is %s" % (f_name, fd))


Code explanation

In the code above, we create a file called file.txt.

  • Line 1: We import the os module.
  • Line 3: We define a variable called f_name that holds the file name.
  • Line 4: We create a file object by using the open() with the read mode (r).
  • Line 5: The file descriptor for the file is obtained using the fileno() method.
  • Line 6: We print the file descriptor.
  • Line 8: We close the file descriptor using the os.close() method.



View all Courses

Keep Exploring