如何判断文件是否是给定目录的后代?
从表面上看,这很简单,我自己也可以轻松实现。只需连续调用 dirname() 即可进入文件路径的每一层并检查每一层,看看它是否是我们要检查的目录。
但符号链接让整个事情陷入混乱。被检查的文件或目录路径上的任何目录都可以是符号链接,并且任何符号链接都可以具有指向其他符号链接的任意符号链接链。此时我的大脑融化了,我不知道该怎么办。我尝试编写代码来处理这些特殊情况,但它很快就会变得太复杂,我认为我做错了。有没有一种相当优雅的方法来做到这一点?
我正在使用 Python,所以任何提及执行此操作的库都会很酷。否则,这是一个与语言无关的问题。
On the surface, this is pretty simple, and I could implement it myself easily. Just successively call dirname() to go up each level in the file's path and check each one to see if it's the directory we're checking for.
But symlinks throw the whole thing into chaos. Any directory along the path of either the file or directory being checked could be a symlink, and any symlink could have an arbitrary chain of symlinks to other symlinks. At this point my brain melts and I'm not sure what to do. I've tried writing the code to handle these special cases, but it soon gets too complicated and I assume I'm doing it wrong. Is there a reasonably elegant way to do this?
I'm using Python, so any mention of a library that does this would be cool. Otherwise, this is a pretty language-neutral problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
os.path.realpath
和os.path .commonprefix
:os.path.realpath
将扩展文件名中的任何符号链接以及..
。 os.path.commonprefix 有点变化无常——它并没有真正测试路径,只是简单的字符串前缀,所以你应该确保你的目录以目录分隔符结尾。如果不这样做,它会声称/the/dirtwo/filename
也在/the/dir
中Use
os.path.realpath
andos.path.commonprefix
:os.path.realpath
will expand any symlinks as well as..
in the filename.os.path.commonprefix
is a bit fickle -- it doesn't really test for paths, just plain string prefixes, so you should make sure your directory ends in a directory separator. If you don't, it will claim/the/dirtwo/filename
is also in/the/dir
Python 3.5 有一个有用的函数
os.path。公共路径
:因此,要检查文件是否是目录的后代,您可以这样做:
与commonprefix不同,您无需担心输入是否有尾部斜杠。
commonprefix
的返回值始终缺少尾部斜杠。Python 3.5 has the useful function
os.path.commonpath
:So to check if a file is a descendant of a directory, you could do this:
Unlike
commonprefix
, you don't need to worry if the inputs have trailing slashes or not. The return value ofcommonprefix
always lacks a trailing slash.在 Python 3 中执行此操作的另一种方法是使用
pathlib
< /a>:请参阅
Path.resolve( )
和路径.父母
。Another way to do this in Python 3 is to use
pathlib
:See documentation for
Path.resolve()
andPath.parents
.