【问题标题】:How can I remove a prefix from a filename in Python? [duplicate]如何从 Python 中的文件名中删除前缀? [复制]
【发布时间】:2017-04-11 01:33:36
【问题描述】:

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

例如,如果外部目录是/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一起使用是测试一个文件是否在另一个文件中的正确方法吗?有没有办法避免我可能需要删除前导斜线的尴尬情况?

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以使用os.path 模块的commonprefixrelpath 来查找两条路径的最长公共前缀。它总是首选使用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
    

    【讨论】:

    • 这也让人感觉不舒服... lstrip 将其参数视为要删除的一组字符,而不是要删除的前缀。如果dir_pathfile_path 未标准化,绝对路径名,这仍然有效吗?
    • 或许relpath 更合适?
    • 看起来this question 接近我的要求。顺便说一句,那里有人指出,显然 commonprefix 已被弃用,有利于 commonpath 功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 2021-11-23
    • 2023-03-13
    • 2012-05-19
    相关资源
    最近更新 更多