Python html 浏览本地 url 路径问题

Python html browsing Local url path issue

我使用 python 生成 html 页。在根文件夹下,我创建了两个文件夹 A 和 B。在 B 中有 b1.html、b2.html 等。在文件夹 A 中,我有 A1.html 和 A2.html 等等。在A1.html中,当生成这样的html时,我根据A1.html中出现的关键字bx创建links到bx.html。

例如:

    stringsCounterNames = re.findall('\[([A-Z].*?)\]',line) #find the keywords
    stringsCounterNames = list(dict.fromkeys(stringsCounterNames)) #remove duplicates
    counter_path="B_Folder"
    if (len(stringsCounterName)>0):

        for stringCounter in stringsCounterNames:
            targetStr=counter_dic[stringCounter]
            target = '<a href="' + counter_path + '/' + targetStr + '.html">' + stringCounter + '<a>'
            line = re.sub(stringCounter, target, line)
            print(line)

在上面的代码中,它会像这样创建一个 link: <a href="B_Folder/b1.html">stringCounter</a> 所以问题是在浏览 A1.html 时,单击 link,它会转到:File:rootFolder/A_Folder/B_Folder/b1.html,因此 link 永远不会像 A_Folder 和 [=31] 一样工作=] 是 rootFolder 下的子文件夹。 我可以将 B_Folder 移到 A_Folder 下来解决问题,但我想整理文件。有没有办法轻松解决这个问题?我尝试将“counter_path”更改为“..B_Folder”或“.B_Folder”,但是没有用。我不能为它放置绝对路径,因为它将迁移到其他根文件夹。谢谢!

相对路径 counter_path="../B_Folder" 应该可以。

您的建议很接近,但 ..B_Folder.B_Folder 都是有效的文件夹名称;因此,相对路径仍然是 root/A_Folder/..B_Folderroot/A_Folder/.B_Folder。但是,文件夹名称 ... 分别指代父文件夹和当前文件夹。将 .. 添加为单独的文件夹(因此将路径更改为 root/A_Folder/../B_Folder)有效:从 root/A_Folder,导航到 .. 会将路径更改为 root,从中你可以导航到 B_Folder.

有关 ... 的更多示例,请参阅 this answer to a Stack Exchange post