Python os.path.sameopenfile() – Checks if given file descriptors refer to the same file

Python os.path.sameopenfile()

Python The os.path.sameopenfile() method is used to check if the given file descriptors refer to the same file.

A file descriptor is a small integer value that corresponds to a file that the current process has open.

A file descriptor represents a resource and serves as a handle to perform various lower-level I/O operations, such as reading, writing, and sending.

For example, standard input is usually file descriptor 0, standard output is usually file descriptor 1, and standard error is usually file descriptor 2. Other files opened by the current process will receive values 3, 4, 5, and so on.

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

Parameters:

fd1: File descriptor.

fd2: File descriptor.

Return Type: This method returns a bool-like value. If file descriptors fd1 and fd2 both refer to the same file, the method returns True; otherwise, it returns False.

Example 1

Use the os.path.sameopenfile() method to check whether the given file descriptors refer to the same file.

# Python program to explain os.path.sameopenfile() method
   
# importing os module
import os
 
#Path
path = "/home/ihritik/Desktop/file1.txt"
 
 
# open the file represented by
# the above given path and get
# the file descriptor associated
# with it using os.open() method
fd1 = os.open(path, os.O_RDONLY)
 
 
# open the file represented by
# the above given path and get
# the file object corresponding
# to the opened file
# using open() method
File = open(path, mode ='r')
 
 
# Get the file descriptor
# associated with the
# file object 'File'
fd2 = File.fileno()
 
 
# check whether the file descriptor
# fd1 and fd2 refer to 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 represented by
# the above given path and get
# the file descriptor associated
# with it using os.open() method
fd3 = os.open(path2, os.O_RDONLY)
 
 
# check whether the file descriptor
# fd1 and fd3 refer to same
# file or not
sameFile = os.path.sameopenfile(fd1, fd3)
 
# Print the result
print(sameFile)
 
 
# close file descriptors
close(fd1)
close(fd2)
close(fd3)

Output:

True
False

Leave a Reply

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