Thursday, December 26, 2024
Google search engine
HomeLanguagesPython | os.close() method

Python | os.close() method

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.close() method in Python is used to close the given file descriptor, so that it no longer refers to any file or other resource and may be reused.
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.close(fd)

Parameter:
fd: A file descriptor, which is to be closed.

Return Type: This method does not return any value

Code: Use of os.close() method to close a file descriptor




# Python program to explain os.close() method 
    
# importing os module 
import os
  
# Path
path = "/home/ihritik/Desktop/file2.txt"
  
  
# open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_WRONLY)
  
  
# Perform some operation
# Lets write a string
s = "GeeksForGeeks: A computer science portal for Lazyroar"
  
# Convert string to bytes object
line = str.encode(s)
  
# Write string to file referred by
# by the file descriptor
os.write(fd, line)
  
  
# close the file descriptor
os.close(fd)
print("File descriptor closed successfully")


Output:

File descriptor closed successfully
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments