【问题标题】:How to get right file path from "../../" and another path with python如何从“../../”获取正确的文件路径和使用 python 的另一个路径
【发布时间】:2016-12-19 06:18:15
【问题描述】:

我正在使用 Python 的 zipfile 和 BeautifulSoup 模块对用户上传的 zip 文件进行内容链接检查。

在 zip 文件中,有一个文件“a.html”,其在 zip 文件中的完整路径是“content/product1/component1/a.html”。文件“a.html”有一个指向另一个 HTML 文件的 <a href="../../product2/component2/b.html"> 链接。

我想知道如何将路径“content/product1/component1/a.html”与“../../product2/component2/b.html”结合起来,得到正确的路径,即“content/product2” /component2/b.html”。所以我可以检查这个文件存在的位置。

我尝试了os.path.join("content/product1/component1/a.html","../../product2/component2/b.html),但没有得到“content/product2/component2/b.html”。有人知道怎么做吗?

【问题讨论】:

    标签: python html django


    【解决方案1】:

    您需要从“content/product1/component1/a.html”中提取路径组件,将其连接到“../../product2/component2/b.html”href,然后对结果进行规范化。

    import os.path
    
    src = "content/product1/component1/a.html"
    srcdir = os.path.dirname(src)
    
    href = "../../product2/component2/b.html"
    url = os.path.normpath(os.path.join(srcdir, href))
    print(url)
    

    输出

    content/product2/component2/b.html
    

    【讨论】:

    • 谢谢。这行得通。为什么我必须先从“content/product1/component1/a.html”中提取路径组件?
    • @user7299363 因为.join假定它的初始参数是目录路径组件,所以它不理解“content/product1/component1/a.html”是一个文件名,类似的注释适用到.normpath。因此,如果您执行os.path.normpath(os.path.join(src, href)),您将获得“content/product1/product2/component2/b.html”。
    • 我现在明白了。感谢您的回答。
    【解决方案2】:

    您可能想尝试使用str.split()(以/ 作为分隔符)并然后在您需要的部分上使用os.path.join()

    【讨论】:

    • 我试试 os.path.join("content/product1/component1/a.html".split("/"), "../../product2/component2/b.html" .split("/")),但我收到一条错误消息。
    • 对,因为 "content/product1/component1/a.html".split("/") 产生 ['content', 'product1', 'component1', 'a.html'] 和"../../product2/component2/b.html".split("/") 产生 ['..', '..', 'product2', 'component2', 'b.html']。如果您尝试将这两个列表直接连接在一起,os.path.join 将被省略号('...')混淆。您必须对列表进行切片才能获得所需的唯一路径部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 2010-10-14
    • 1970-01-01
    • 2020-04-23
    • 2011-03-21
    • 2016-12-12
    相关资源
    最近更新 更多