python - 如何使用python从 "../../"和另一个路径获取正确的文件路径

标签 python html django

我正在使用 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/

相关文章:

python - 如何根据输入创建不同的对象?

javascript - 如何使用ajax将select标签的值发送到驻留在同一页面上的php

javascript - 列内的图形元素在最大高度上失败

python - 如何运行外部命令(Django)来覆盖服务器中的文件?

python - 在实例方法中更改类实例

javascript - 如何释放网页上的系统资源/CPU使用率?

python - 在 django 管理过滤器 list_filter 中选择多个选项?

python - 在 Pandas DF 的不同列中计算运行总计

python - dask 和 pandas 数据帧中 apply 的不兼容性

python - numpy/scipy/python 中的快速 K 步折扣