os.close() method is used to close an open file descriptor. Once a file descriptor is closed, it can no longer be used for reading, writing or other I/O operations.
Example: In the following example, we open a file using os.open(), get its file descriptor and then close it using os.close().
import os
fd = os.open("sample.txt", os.O_RDONLY)
os.close(fd)
print("File descriptor closed")
Output
File descriptor closed
Explanation: os.open() returns a file descriptor and os.close(fd) closes it so that the resource is released.
Syntax
os.close(fd)
- Parameters: fd - The file descriptor to be closed.
- Return Value: os.close() does not return any value.
Examples
Example 1: The following example opens a file in read mode and then closes its file descriptor.
import os
fd = os.open("sample.txt", os.O_RDONLY)
print("Descriptor:", fd)
os.close(fd)
Output
Descriptor: 3
Explanation: os.open() creates a file descriptor and stores it in fd. The statement os.close(fd) closes that descriptor.
Example 2: The following example opens a file in write mode, writes data to it and then closes the file descriptor.
import os
fd = os.open("data.txt", os.O_WRONLY | os.O_CREAT)
os.write(fd, b"Hello Python")
os.close(fd)
print("Data written successfully")
Output
Data written successfully
Explanation: os.write(fd, b"Hello Python") writes data to the file associated with fd. After writing, os.close(fd) releases the file descriptor.
Example 3: The following example opens two files and closes both file descriptors separately.
import os
fd1 = os.open("a.txt", os.O_RDONLY)
fd2 = os.open("b.txt", os.O_RDONLY)
os.close(fd1)
os.close(fd2)
print("Both descriptors closed")
Output
Both descriptors closed
Explanation: os.close(fd1) closes the first file descriptor and os.close(fd2) closes the second one, releasing both resources.