python - 如何在python中获取路径的左侧部分?

标签 python path

如何获取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/

相关文章:

python - 程序运行正常,但无法导入并出现 IndexError

python - TensorFlow - tf.VariableScope 和 tf.variable_scope 之间的区别

php - MySQL 中有等效的 basename() 吗?

python - 如何消除两个数据集的 Leibler 分歧

python - 将新的 ManyToManyField 默认值追溯设置为现有模型

c++ - 使用 boost::filesystem::path 获取绝对路径

php - 使用 "./"的相对路径

string - Matlab能否去掉URL中的路径,只留下域名部分?

macos - 在 macOS 上,如何找到使用 “open” 命令打开的应用程序路径?

python - 如何使嵌入式Python解释器的本地空间与全局空间共享一些变量