我正在编写一个脚本,我必须在两行之间插入一行。例如:
<%= link_to 'Delete', user_task_path(current_user, task.id),
data: { confirm: 'Are you sure?' }, :method => :delete, remote: true %>
我正在尝试下面提到的代码,但我无法在文件中写任何内容。
<tag1>
<subtag1>
Line 1 - with some text
Line 2 - with some text
</subtag> - #closing of subtag
**--> here i have (between closure of subtag and tag1) to insert a new tag (3 lines, opening tag, body and closing tag)**
</tag1>
有人可以让我知道在上面的代码中我做错了什么,或者编写代码在python中的文件中的两行之间插入一行代码?
答案 0 :(得分:0)
根据 jonrsharpe 的评论,最容易理解的方法是阅读整个文件,然后在需要的地方插入行:
# Let's read our input file into a variable
with open('input.html', 'r') as f:
in_file = f.readlines() # in_file is now a list of lines
# Now we start building our output
out_file = []
for line in in_file:
out_file.append(line) # copy each line, one by one
if '</subtag>' in line: # add a new entry, after a match
out_file.append(' <some new tag>text1</some new tag>\n')
# Now let's write all those lines to a new output file.
# You would re-write over the input file now, if you wanted!
with open('out.html', 'w') as f:
f.writelines(out_file)
我从这个文件开始:
<tag1>
<subtag1>
Line 1 - with some text
Line 2 - with some text
</subtag>
</tag1>
结束我的脚本产生了这个:
<tag1>
<subtag1>
Line 1 - with some text
Line 2 - with some text
</subtag>
<some new tag>text1</some new tag>
</tag1>
我希望有所帮助!