我正在使用 Python 的 zipfile 和 BeautifulSoup 模块对用户上传的 zip 文件进行内容链接检查。
在zip文件中,有一个文件“a.html”,其在zip文件中的完整路径为“content/product1/component1/a.html”。文件“a.html”有一个 <a href="../../product2/component2/b.html">
链接到另一个 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”。有谁知道该怎么做吗?
最佳答案
您需要从“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
关于python - 如何使用python从 "../../"和另一个路径获取正确的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41216774/