如何找出一个文件夹是否是硬链接并获取其真实路径

2024-10-01 15:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出一个文件夹是否是另一个文件夹的硬链接,在这种情况下,找到它的真实路径。在

我用python做了一个简单的例子(符号链接.py)公司名称:

#python 3.4
import os
dirList = [x[0] for x in os.walk('.')]

print (dirList)

for d in dirList:
    print (os.path.realpath(d), os.path.islink(d))

"""
Given this directories structure:
<dir_path>\Example\
    <dir_path>\Example\symLinks.py
    <dir_path>\Example\hardLinkToF2 #hard link pointing to <dir_path>\Example\FOLDER1\FOLDER2
    <dir_path>\Example\softLinkToF2 #soft link pointing to <dir_path>\Example\FOLDER1\FOLDER2
    <dir_path>\Example\FOLDER1
        <dir_path>\Example\FOLDER1\FOLDER2

The output from executing: C:\Python34\python <dir_path>\Example\symLinks.py is:
['.', '.\\FOLDER1', '.\\FOLDER1\\FOLDER2', '.\\hardLinkToF2']
<dir_path>\Example False
<dir_path>\Example\FOLDER1 False
<dir_path>\Example\FOLDER1\FOLDER2 False
<dir_path>\Example\hardLinkToF2 False
"""

在这个例子中操作系统路径.islink对于硬链接或软链接,始终返回False。 另一方面,操作系统路径.realpath返回软链接的实际路径,而不是硬链接的实际路径。在

我在windows8中使用python3.4创建了这个示例。 我不知道我是不是做错了什么事,或者是否有别的方法可以实现它。在


Tags: pathpy路径文件夹falseforos链接
1条回答
网友
1楼 · 发布于 2024-10-01 15:31:43

不是太苛刻,但我花了1分钟在谷歌上搜索,得到了所有的答案。提示提示。在

要判断它们是否是硬链接,必须扫描所有文件,然后比较它们的os.stat结果,看它们是否指向同一个inode。示例:

https://gist.github.com/simonw/229186

对于Windows上python中的符号链接,它可能更为复杂。。。但幸运的是,这个问题已经得到了回答:

Having trouble implementing a readlink() function

因为你不能用符号连接代替每个ranger报告中的符号连接。–影游侠

https://bugs.python.org/issue29250

相关问题 更多 >

    热门问题