如何从“../../”和python的另一个路径获取正确的文件路径

时间:2016-12-19 06:18:16

标签: python html django

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

在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”。有谁知道怎么做?

2 个答案:

答案 0 :(得分:1)

您需要从&#34; content / product1 / component1 / a.html&#34;中提取路径组件,将其加入&#34; ../../ product2 / component2 / b.html&# 34; 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

答案 1 :(得分:0)

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