Open In App

Python | os.closerange() method

Last Updated : 18 Jun, 2019
Like Article

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.

os.closerange() method in Python is used to close all file descriptors in the range fd_low (inclusive) to fd_high (exclusive). Any error occurred while closing any of the file descriptor in the given range is ignored.

A file descriptor is small integer value that corresponds to a file or other input/output resource, such as a pipe or network socket. A File descriptor is an abstract indicator of a resource and act as handle to perform various lower level I/O operations like read, write, send etc.

For Example: Standard input is usually file descriptor with value 0, standard output is usually file descriptor with value 1 and standard error is usually file descriptor with value 2.
Further files opened by the current process will get the value 3, 4, 5 an so on.

Syntax: os.closerange(fd_low, fd_high)

fd_low: The Lowest file descriptor to be closed.
fd_high: The highest file descriptor to be closed.

Return Type: This method does not return any value

Code: Use of os.closerange() method to close file descriptors in the given range

# Python program to explain os.close() method 
# importing os module 
import os
# File Paths to be opened
path1 = "/home/ihritik/Desktop/file1.txt"
path2 = "/home/ihritik/Desktop/file2.txt"
path3 = "/home/ihritik/Desktop/file3.txt"
path4 = "/home/ihritik/Desktop/file4.txt"
# open the files and get
# the file descriptor associated
# with it using method
fd1 =, os.O_WRONLY | os.O_CREAT)
fd2 =, os.O_WRONLY | os.O_CREAT)
fd3 =, os.O_WRONLY | os.O_CREAT)
fd4 =, os.O_WRONLY | os.O_CREAT)
# Perform some operation
# Lets write a string
s = "GeeksForGeeks: A computer science portal for geeks"
# Convert string to bytes object
line = str.encode(s)
# Write above string to all file
os.write(fd1, line)
os.write(fd2, line)
os.write(fd3, line)
os.write(fd4, line)
# close all file descriptors
# using os.closerange() method
fd_low = min(fd1, fd2, fd3, fd4)
fd_high = max(fd1, fd2, fd3, fd4)
os.closerange(fd_low, fd_high + 1)
print("All file descriptor closed successfully")


All file descriptor closed successfully

Note: os.closerange() method is equivalent to following python code:

for fd in range(fd_low, fd_high):
    except OSError:

However os.closerange() method works faster than above code.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads