Python OS file/directory os.closerange() method

Python OS File/Directory os.closerange() Method

Description

The closerange() method closes all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. This method was introduced in Python 2.6.

Syntax

The syntax of the closerange() method is as follows:

os.closerange(fd_low, fd_high)

Parameters

  • fd_low − This is the lowest file descriptor to be closed.
  • fd_high − This is the highest file descriptor to be closed.

This function is equivalent to:

for fd in xrange(fd_low, fd_high):
try:
os.close(fd)
except OSError:
pass

Return Value

This method does not return any value.

Example

The following example shows the usage of the closerange() method.

import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR | os.O_CREAT )

# Write one string
line="this is test"
# string needs to be converted to a byte object
b=str.encode(line)
os.write(fd, b)
# Close a single opened file
os.closerange( fd, fd)

print ("Closed all the files successfully!!")

This creates the given file foo.txt and then writes the given content to it. This produces the following result −

Closed all the files successfully!

Leave a Reply

Your email address will not be published. Required fields are marked *