Python | os.path.sameopenfile () method



os.path.sameopenfile() in Python is used to check if specified file descriptors refer to the same file or not … 
File descriptor — it is a small integer value that corresponds to a file that was opened by the current process. 
A file descriptor specifies a resource and acts as descriptors to perform various lower level I / O operations such as reading, writing, sending, etc.
For example: standard input usually a file descriptor with a value of 0, standard output is usually a file descriptor with a value of 1, and standard error is usually a file descriptor with a value of 2. Other files opened by the current process will get the value 3, 4, 5 and soon.

Syntax: os.path.sameopenfile (fd1, fd2)

Parameter:
fd1 : A file descriptor.
fd2 : A file descriptor.

Return Type: This method returns a Boolean value of class bool. This method returns True if both file descriptor fd1 and fd2 refer to the same file otherwise returns false.

Code: using the os.path.sameopenfile () method to checks whether the specified file descriptors refer to the same file or not.

# Python program to explain the os.path.sameopenfile () method

 
# import of the os module

import os

 
# Path

path = " / home / ihritik / Desktop / file1.txt "

  

 
# open the file provided
# the above path and get
# file descriptor linked
# using the os.open () method

fd1 = os. open (path, os.O_RDONLY)

 

 
# open the file provided
# above path and get
# file object matching
# to the open file
# using open () method

File = open (path, mode   = `r` )

 

 
# Get file descriptor
# related to
# file object & # 39; File & # 39;

fd2 = File .fileno ()

 

 
# check if there is a file descriptor
# fd1 and fd2 refer to the same
# file or not

sameFile = os.path.sameopenfile (fd1, fd2)

 
# Print the result

print (sameFile)

 

 
# Path

path2 = "/ home / ihritik / Documents / sample.txt "

  

  
# open the file provided
# above path and get
# file descriptor linked
# using os.open () method

fd3 = os. open (path2, os.O_RDONLY)

 

  
# check if there is a file descriptor
# fd1 and fd3 link to the same
# file or not

sameFile = os.path.sameopenfile (fd1, fd3)

  
# Print the result

print (sameFile)

  

  
# close file descriptors
close (fd1)
close (fd2)
close (fd3)

Exit :

 True False 

Link: https://docs.python.org/3/library/os.path.html