如何获取python中相对路径最左边的部分?
我从这样的事情开始:
/var/tmp/workdir/1/foo/bar/test.jpg
然后我删除了一些得到:
1/foo/bar/test.jpg
使用:
rel_path = os.path.relpath(path,base_dir)
现在我怎样才能得到最左边的部分 - “1”?
我只能找到从右边开始的工具,但在这种情况下,我想要最左边的东西,因为它与用户 ID 相对应。另外我想避免从右侧开始,因为可能会有更多的子目录。
最佳答案
如果名称包含 os.path.sep
(当然是转义),使用 str.split
可能会给出不正确的结果。恕我直言,最安全的解决方案是:
basename = None # guards against UnboundLocalError in case of empty rel_path
while rel_path:
rel_path, basename = os.path.split(rel_path)
print basename # this will be the leftmost component
关于python - 如何在python中获取路径的左侧部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26328650/