【问题标题】:How to make an absolute path relative to another?如何制作相对于另一个的绝对路径?
【发布时间】:2016-07-07 21:36:01
【问题描述】:

假设我在 Python 中有两个文件路径作为字符串,例如,假设它们是这两个:

C:/Users/testUser/Program/main.py
C:/Users/testUser/Program/data/somefile.txt

有没有办法使用os 模块根据第一个模块生成相对URL?比如喂上面两个来生产:

data/somefile.txt

我意识到这可以通过字符串操作实现,通过在末尾拆分文件并将第一个字符串从第二个字符串中删除,但是有没有更健壮的方法,可能使用 python os 模块?

【问题讨论】:

    标签: python filepath


    【解决方案1】:

    感谢下面评论中的 MPlanchard,这是完整的答案:

    import os
    
    string1 = "C:/Users/testUser/Program/main.py"
    string2 = "C:/Users/testUser/Program/data/somefile.txt"
    
    os.path.relpath(string2, os.path.dirname(string1))
    

    【讨论】:

    • 我认为你想要做的是 os.path.relpath(string2, os.path.dirname(string1)) 来获得询问者指定的输出。
    猜你喜欢
    • 2011-03-21
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2016-04-22
    相关资源
    最近更新 更多