猿问

Python 在特定文本之前插入文本

我想将 html 文件(myhtml.html)附加到页脚标记之前的现有 html(abc.html)中。


这是我用来执行此操作的代码:


with open("abc.html", "r+") as f:

    a = [x.rstrip() for x in f]

    print(a)

    index = 0

    for item in a:

        if item.startswith("<footer"):

        

            with open("myhtml.html","r") as f_insert:

                a_insert = [x_insert.rstrip() for x_insert in f_insert]

                

                index_insert = 0

                print(index)

                print(index_insert)

                for item_insert in a_insert:

                    a.insert(index, item_insert) 

                    index +=1

            break

        index += 1

这是我想要附加 html 文件的 HTML 文件的外观:


</div></div><footer><div class=container-fl><div class="footer-text"><p class="text-center">

您会注意到页脚标记不在行的开头,因此我无法在页脚标记之前附加我的 html。有办法解决这个问题吗?


哔哔one
浏览 116回答 1
1回答

拉莫斯之舞

如果您只需要行列表并且不需要更新输入文件,那么:# read oncewith open("myhtml.html","r") as f_insert:&nbsp; &nbsp; a_insert = [line.rstrip() for line in f_insert]with open("abc.html", "r") as f:&nbsp; &nbsp; a = [line.rstrip() for line in f]&nbsp; &nbsp; for i, line in enumerate(a):&nbsp; &nbsp; &nbsp; &nbsp; if "<footer" in line:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[i:i] = a_insert&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; breaka是结果list。然而,如果你想更新输入文件,下面的方法会更直接:# read oncewith open("myhtml.html","r") as f_insert:&nbsp; &nbsp; a_insert = f_insert.readlines() # keep whitespace at endwith open("abc.html", "r+") as f:&nbsp; &nbsp; a = f.readlines() # keep whitespace at end&nbsp; &nbsp; for i, line in enumerate(a):&nbsp; &nbsp; &nbsp; &nbsp; if "<footer" in line:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[i:i] = a_insert&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; f.seek(0, 0) # position to start of file&nbsp; &nbsp; for line in a:&nbsp; &nbsp; &nbsp; &nbsp; f.write(a)
随时随地看视频慕课网APP

相关分类

Python
我要回答