检查目录是否是符号链接? [英] Check if directory is symlink?

查看:54
本文介绍了检查目录是否是符号链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

os 中有一个函数os.path.islink(PATH),它检查PATH 是否是符号链接.但是如果当 PATH 是某个目录的符号链接时失败.相反——python 认为它是目录 (os.path.isdir(PATH)).那么如何检查目录是否为链接?

In os there's a function os.path.islink(PATH) which checks if PATH is symlink. But if fails when PATH is a symlink to some directory. Instead -- python thinks it is directory (os.path.isdir(PATH)). So how do I check if a dir is link?

编辑:

以下是 bash 的想法:

~/scl/bkbkshit/Teaching: file 2_-_Classical_Mechanics_\(seminars\)
2_-_Classical_Mechanics_(seminars): symbolic link to `/home/boris/wrk/tchn/2_-_Classical_Mechanics_(seminars)'

这里是 python 的想法:

In [8]: os.path.islink("2_-_Classical_Mechanics_(seminars)/")
Out[8]: False

推荐答案

发生这种情况是因为您在文件名末尾放置了一个斜杠.

This happens because you put a slash at the end of the filename.

os.path.islink("2_-_Classical_Mechanics_(seminars)/")
                                                  ^

尾部斜杠使操作系统跟随链接,因此结果是目标目录,而不是链接.如果删除斜杠,islink 将返回 True.

The trailing slash causes the OS to follow the link, so that the result is the target directory which is not a link. If you remove the slash, islink will return True.

同样的事情也发生在 Bash 中:

The same thing happens in Bash as well:

g@ubuntu:~$ file aaa
aaa: symbolic link to `/etc'
g@ubuntu:~$ file aaa/
aaa/: directory

这篇关于检查目录是否是符号链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆