Python os.close() Method



The Python os.close() method closes the specified file descriptor. File descriptors in Python are identifiers that represents the open files in the os kernel and are kept in a table of files.

Typically, file descriptors have non-negative values. Negative results denote an error or a "no value" condition. The main things they assist with are accessing files and other input/output devices like network sockets or pipes.

Syntax

Following is the syntax of Python os.close() method −

os.close(fd);

Parameters

  • fd − This is the file descriptor of the file.

Return Value

This method does not return any value.

Example

The following example shows the usage of Python os.close() method. Here we are creating a file descriptor 'os.O_RDWR|os.O_CREAT'. Then we write a string "This is test" in the file. Thereafter, we are closing the file using this method.

import os, sys
import os, sys
# Open a file
fd = os.open("foo.txt", os.O_RDWR|os.O_CREAT)
# Write one string
string = "This is test"
x = str.encode(string)
os.write(fd,x)
# Close opened file
os.close(fd)
print ("Closed the file successfully!!")

When we run above program, it produces following result −

Closed the file successfully!!

Example

In the example given below we are creating a file descriptor 'r'. This means reading the file.

import os
file = "code.txt"
file_Object = open(file, "r")
fd = file_Object.fileno()
print("The descriptor of the file for %s is %s" % (file, fd))
os.close(fd)

While executing the above code we get the following output −

The descriptor of the file for code.txt is 3

Example

If the file descriptor is not valid, then this method raises the EBADF error.

import os
# Creating a file descriptor
filedesc = os.open("code.txt", os.O_RDWR)
# closing an invalid file descriptor
os.close(filedesc + 1)

Following is an output of the above code −

Traceback (most recent call last):
  File "/home/sarika/Desktop/chown.py", line 5, in <module>
    os.close(filedesc + 1)
OSError: [Errno 9] Bad file descriptor
os_file_methods.htm
Advertisements