Python os.path.samestat() Method

Python os.path.samestat() method is used to check if two stat tuples refer to the same file or directory.

The stat tuples contain detailed information about a file or directory, such as size, modification time, and inode number. This method compares these details to determine if two tuples refer to the same file.

It returns True if the stat tuples stat1 and stat2, typically obtained from os.stat(), os.fstat(), or os.lstat(), refer to the same file or directory.

Syntax

os.path.samestat(stat1, stat2)

Parameters

Name Description
stat1 A stat tuple representing the status of a file or directory.
stat2 Another stat tuple represents the status of a file or directory.

Return value

It returns True if stat1 and stat2 refer to the same file or directory and False otherwise.

Example 1: Checking if two paths refer to the same file

Python os.path.samestat() - Checking if two paths refer to the same file

Our path1 is “/Users/krunallathiya/Desktop/Code/pythonenv/env/file.txt”

Screenshot of file.txt path

Our path2 is “/Users/krunallathiya/Desktop/Code/pythonenv/env/symlink_file_txt”

Screenshot of symlink file

import os
path1 = '/Users/krunallathiya/Desktop/Code/pythonenv/env/file.txt'

# A symlink to file.txt
path2 = '/Users/krunallathiya/Desktop/Code/pythonenv/env/symlink_file_txt'

stat1 = os.stat(path1)
stat2 = os.stat(path2)

print(os.path.samestat(stat1, stat2))

Output

True

Example 2: Comparing Different Files

Comparing Different Files

import os

path1 = '/Users/krunallathiya/Desktop/Code/pythonenv/env/file.txt'
path2 = '/Users/krunallathiya/Desktop/Code/pythonenv/env/new.txt'

stat1 = os.stat(path1)
stat2 = os.stat(path2)

print(os.path.samestat(stat1, stat2))

Output

False

That’s all!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.