Python os.path.samefile() Method

Python os.path.samefile() method is used to check if two pathnames refer to the same file or directory.

This method helps check if two paths, which may appear different as strings, point to the same file or directory.

It resolves any symbolic links in the paths, comparing the actual files they point to.

The os.path.samefile() method is available on both Unix and Windows. On Unix, it compares device and inode numbers; on Windows, it compares the paths after resolving any symbolic links.

Syntax

os.path.samefile(path1, path2)

Parameters

Name Description
path1 (string) The input path
path2 (string) The path you want to compare with the input path

Return value

This method compares two pathnames and returns True if they refer to the same file or directory (i.e., they have the same device and inode numbers) and False otherwise.

Visual representation

Figure of Python os.path.samefile() Method

Example 1: Comparing two different paths to the same file

Let’s say we have two different types of files which point to the same file.

  1. Normal text file
  2. Symlink file that points to the normal text file

Technically, both files point to the same file, but the paths differ.

Here is a standard text file: file.txt

Screenshot of normal text file

Here is a symlink file (symlink_file_txt) that points to the file.txt.

Screenshot of symlink file that points to file

Let’s compare both files:

import os

# These two paths may refer to the same file
path1 = '/Users/krunallathiya/Desktop/Code/pythonenv/env/file.txt'
path2 = '/Users/krunallathiya/Desktop/Code/pythonenv/env/symlink_file_txt'

print(os.path.samefile(path1, path2))

Output

True

It returned True because both paths refer to the same file.

Example 2: Comparing Two Distinct Files

Visual representation of Comparing Two Distinct Files

import os

# These two paths refers to the different file
path1 = '/Users/krunallathiya/Desktop/Code/pythonenv/env/file.txt'
path2 = '/Users/krunallathiya/Desktop/Code/pythonenv/env/new.txt'

print(os.path.samefile(path1, path2))

Output

False

That’s all!

Leave a Comment

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