python - 如何从 Python 中的文件名中删除前缀?

标签 python

<分区>

我想编写一个脚本来接收目录路径和该目录中包含的文件路径(可能嵌套了很多目录)并返回该文件相对于外部目录的路径。

例如,如果外部目录是/home/hugomg/foo,内部文件是/home/hugomg/foo/bar/baz/unicorns.txt我希望脚本输出 bar/baz/unicorns.txt

现在我正在使用 realpath 和字符串操作:

import os

dir_path = "/home/hugomg/foo"
file_path = "/home/hugomg/foo/bar/baz/unicorns.py"

dir_path = os.path.realpath(dir_path)
file_path = os.path.realpath(file_path)

if not file_path.startswith(dir_path):
    print("file is not inside the directory")
    exit(1)

output = file_path[len(dir_path):]
output = output.lstrip("/")
print(output)

但是有没有更强大的方法来做到这一点?我不确定我当前的解决方案是否是执行此操作的正确方法。将 startswith 与 realpath 一起使用是测试一个文件在另一个文件中的正确方法吗?有没有办法避免我可能需要删除的前导斜线的尴尬情况?

最佳答案

您可以使用os.path 模块的commonprefixrelpath 来查找两条路径的最长公共(public)前缀。它总是首选使用 realpath

import os
dir_path = os.path.realpath("/home/hugomg/foo")
file_path = os.path.realpath("/home/hugomg/foo/bar/baz/unicorns.py")
common_prefix = os.path.commonprefix([dir_path,file_path])

if common_prefix != dir_path:
    print("file is not inside the directory")
    exit(1)
print(os.path.relpath(file_path, dir_path))

输出:

bar/baz/unicorns.txt

关于python - 如何从 Python 中的文件名中删除前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43335356/

相关文章:

python - Plotly:使用 plotly express line 时如何在 hoverinfo 中格式化日期?

python - 产量(x)与(产量(x)): parentheses around yield in python

python - 使用 BeautifulSoup 通过超链接访问表格数据

python - 如何在Python中应用闭-开和控制反转原理?

Python:比较字符串的可靠方法

python - 检查用户输入的 IP 地址是否有效

python - 如何从随机加权矩阵中选择元素

Python 3 + Selenium : How to find this element by xpath?

python - 如何在依赖于两个变量的函数中仅对一个变量使用 'for' 循环?

python - 未绑定(bind)的 super 对象,super(self, self)