Python| os.path.samefile() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.samefile()
方法用于检查给定的两个路径名是否引用相同的文件或目录。这是通过比较给定路径的设备号和 i 节点号来确定的。
该方法利用os.stat()
方法获取给定路径的设备号和 i-node 号。因此,如果os.stat()
调用在任一路径名上失败,则会引发异常。
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.
代码:使用 os.path.samefile() 方法检查给定路径是否引用相同的文件或目录。
# Python program to explain os.path.samefile() method
# importing 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 whether the given
# paths refer to the same
# file or directory or not
areSame = os.path.samefile(path1, sym_link)
# Print the result
print(areSame)
# In above example, sym_link is
# a symbolic link which refers
# to path1, so os.path.samefile() method
# will return True as both refer
# to same file
# First Path
path2 = "/home / ihritik / GeeksForGeeks"
# Second path
# consider the current working directory
# is "/home / ihritik"
path3 = os.path.join(os.getcwd(), "GeeksForGeeks")
# Check whether the given
# paths refer to the same
# file or directory or not
areSame = os.path.samefile(path2, path3)
# Print the result
print(areSame)
True
True
参考: https://docs。 Python.org/3/library/os.path.html