如何获取python中相对路径的最左侧部分?
我从这样的事情开始:
/var/tmp/workdir/1/foo/bar/test.jpg
然后我删除了其中的一些内容:
1/foo/bar/test.jpg
使用:
rel_path = os.path.relpath(path,base_dir)
现在如何获得最左边的部分-“ 1”?
我只能从右侧找到工具,但是在这种情况下,我需要最左边的东西,因为它与用户ID对应。我也想避免从右边去,因为可能会有更多的子目录。
str.split
如果名称包含os.path.sep
(使用转义符),则使用可能会给出错误的结果。最安全的解决方案是:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句