[英]Python Insert text before a specific text
I want to append a html file(myhtml.html) into an existing html(abc.html) before the footer tag.我想在页脚标记之前将一个 html 文件(myhtml.html)附加到现有的 html(abc.html)中。
Here is the code that I use to do that:这是我用来执行此操作的代码:
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
This is how the HTML file where I want to append my html file looks:这是我想要附加我的 html 文件的 HTML 文件的外观:
</div></div><footer><div class=container-fl><div class="footer-text"><p class="text-center">
You would notice that footer tag is not at start of the line and hence I am not able to append my html before the footer tag.您会注意到页脚标记不在行的开头,因此我无法在页脚标记之前附加我的 html。 Is there a way to resolve this?有没有办法解决这个问题?
If you just need a list of lines and don't need to update the input file, then:如果您只需要行列表而不需要更新输入文件,则:
# read once
with open("myhtml.html","r") as f_insert:
a_insert = [line.rstrip() for line in f_insert]
with open("abc.html", "r") as f:
a = [line.rstrip() for line in f]
for i, line in enumerate(a):
if "<footer" in line:
a[i:i] = a_insert
break
a
is the resultant list
. a
是结果list
。
However, if you want to update the input file, the following would be more direct:但是,如果要更新输入文件,则以下内容会更直接:
# read once
with open("myhtml.html","r") as f_insert:
a_insert = f_insert.readlines() # keep whitespace at end
with open("abc.html", "r+") as f:
a = f.readlines() # keep whitespace at end
for i, line in enumerate(a):
if "<footer" in line:
a[i:i] = a_insert
break
f.seek(0, 0) # position to start of file
for line in a:
f.write(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.