假设我有两个路径:第一个路径(可能是文件或文件夹路径):file_path
,第二个(可能只是文件夹路径):folder_path
。我想确定一个对象是否与 file_path
并置位于与 folder_path
搭配的对象内部.
我有这样做的想法:
import os
...
def is_inside(file_path, folder_path):
full_file_path = os.path.realpath(file_path)
full_folder_path = os.path.realpath(folder_path)
return full_folder_path.startswith(full_file_path)
但恐怕这种方法存在一些陷阱。另外我认为必须有一种更漂亮的方法来做到这一点。
该解决方案必须在 Linux 上运行,但如果您向我提出一些跨平台的技巧,那就太好了。
最佳答案
使用os.path.commonprefix
。这是一个基于您的想法的示例。
import os.path as _osp
def is_inside(file_path, folder_path):
full_file_path = _osp.realpath(file_path)
full_folder_path = _osp.realpath(folder_path)
return _osp.commonprefix([full_file_path, full_folder_path]) == \
full_folder_path
关于python - 如何判断指定的文件是否位于指定的文件夹内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4843782/