Python os.closerange() Method
-
Syntax of the
os.closerange()
Method -
Example 1: Working With the
os.closerange()
Method in Python -
Example 2: Use an Equivalent of the
os.closerange()
Method in Python -
Example 3: Standard Range of the
os.closerange()
Method in Python

Python os.closerange()
method is an efficient way of closing all file descriptors from fd_low
(inclusive) to fd_high
(exclusive). Any errors from fd_low
to fd_high
while closing file descriptors are ignored.
Syntax of the os.closerange()
Method
os.closerange(fd_low, fd_high)
Parameters
fd_low |
The lower boundary of the range of the file descriptor to be closed. |
fd_high |
The upper boundary of the range of the file descriptor to be closed. |
Return
In the execution process, this method does not return any value.
Example 1: Working With the os.closerange()
Method in Python
import os
path1 = "file1.txt"
path2 = "file2.txt"
path3 = "file3.py"
path4 = "file4.csv"
fd1 = os.open(path1, os.O_WRONLY | os.O_CREAT)
fd2 = os.open(path2, os.O_WRONLY | os.O_CREAT)
fd3 = os.open(path3, os.O_WRONLY | os.O_CREAT)
fd4 = os.open(path4, os.O_WRONLY | os.O_CREAT)
string = "Hello, World!"
line = str.encode(string)
os.write(fd1, line)
os.write(fd2, line)
os.write(fd3, line)
os.write(fd4, line)
fd_low = min(fd1, fd2, fd3, fd4)
fd_high = max(fd1, fd2, fd3, fd4)
os.closerange(fd_low, fd_high + 1)
print("Closed all the files successfully!")
Output:
Closed all the files successfully!
A file descriptor fd
is an abstract integer value that acts as a handle to perform various lower-level I/O operations such as read, write, send, etc.
Example 2: Use an Equivalent of the os.closerange()
Method in Python
import os
fd = os.open( "file.txt", os.O_RDWR|os.O_CREAT )
string = "Hello, World!"
line = str.encode(string)
os.write(fd, line)
os.close(fd)
print ("Closed all the files successfully!")
Output:
Closed all the files successfully!
The os.closerange()
is a more efficient method than os.close()
because it allows flexibility in the file descriptors range.
Example 3: Standard Range of the os.closerange()
Method in Python
import os
fd = os.open( "file.txt", os.O_RDWR|os.O_CREAT )
os.closerange( 0, 1)
print ("Closed all the files successfully!")
Output:
Closed all the files successfully!
The standard input is a file descriptor with value 0
, whereas the standard output is a file descriptor with value 1
. Moreover, the standard error is usually a file descriptor with a value of 2
.
Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.
LinkedIn