Python | os.path.samefile () method



os.path.samefile() in Python is used to check if the specified two paths refer to the same file or directory or not. This is determined by comparing the device number and the i-node number of the given paths. 
This method uses os.stat () exception if any os.stat () call os.stat () will fail for any of the paths.

Syntax: os.path.samefile (path1, path2)

Parameter:
path1 : A path-like object representing the first file system path.
path2 : A path-like object representing the second file system path.

A path-like object is either a string or bytes object representing a path.

Return Type : This method returns a Boolean value of class bool. This method returns True if both path refer to the same file otherwise returns False.

Code: Using the os.path.samefile () method to check if specified paths to the same file or directory.

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

 
# import of the os module

import os

 
# Path

path1 = "/ home / ihritik / Documents / file (original) .txt "

  
# Create a symbolic link

 sym_link = "/ home / ihritik / Desktop / file (shortcut) .txt"

os.symlink (path1, sym_link)

 
# Check if the given one matches
# paths link to the same
# file or directory or not

areSame = os.path.samefile (path1, sym_link)

 
# Print result

print (areSame)

 
# In the above example, sym_link
# symlink that links
# to path1, poet the os.path.samefile () method
# will return True, since both refer to
# to the same file

 

 
# First path

path2 = "/ home / ihritik / GeeksForGeeks"

 
# Second path
# view the current working directory
# is & quot; / home / ihritik & quot ;

path3 = os.path. join (os.getcwd (), "GeeksForGeeks" )

 
# Check if the given matches
  # paths refer to the same
# file or directory or not

areSame = os.path.samefile (path2, path3)

 
# Print result

print (areSame)

Output:

 True True 

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