如何从“/”获取正确的文件路径/&引用;还有另一条python路径
我正在使用Python的zipfile和BeautifulSoup模块对用户的上传zip文件进行内容链接检查 在zip文件中,有一个文件“a.html”,它在zip文件中的完整路径是“content/product1/component1/a.html”。文件“a.html”具有指向另一个html文件的如何从“/”获取正确的文件路径/&引用;还有另一条python路径,python,html,django,Python,Html,Django,我正在使用Python的zipfile和BeautifulSoup模块对用户的上传zip文件进行内容链接检查 在zip文件中,有一个文件“a.html”,它在zip文件中的完整路径是“content/product1/component1/a.html”。文件“a.html”具有指向另一个html文件的链接 我想知道如何将路径“content/product1/component1/a.html”与“../../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”。有人知道怎么做吗?您可能想尝试使用(以/
作为分隔符),然后使用os.path.join()
在您需要的部件上。您需要从“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”。谢谢你的回答。我尝试了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将被省略号(“…”)混淆。您必须对列表进行切片,以获得所需的路径的唯一部分。