[英]How to find and add new line in python if have spaces before
我的代碼有問題。 在文件中的文本之前的“line1 和 line2”中有一些空格,我如何忽略它們?
前任。:
<server xmlns="urn:jboss:domain:1.2">
</handlers>
</root-logger>
</subsystem>
<subsystem xmlns="urn:jboss:domain:naming:1.1">
<bindings>
這些空格會干擾代碼查找 line1 和 line2。
下面是我的代碼
with open("xxx", "r+") as f:
a = [x.rstrip() for x in f]
index = 1
line1 = '<subsystem xmlns="urn:jboss:domain:naming:1.1">'
line2 = "<bindings>"
for item in a:
if item.startswith(line1 and line2):
a.insert(index, '<simple name="java:global/nbs/app/portal/config/routes"\n\tvalue="C:\\nbs\\app\\portal\\routes.properties"/>')
break
index += 1
f.seek(0)
for line in a:
f.write(line + "\n")
改變這個
a = [x.rstrip() for x in f]
進入這個
a = [x.strip() for x in f]
說明: rstrip()
只修剪右側的空格,您需要的是strip()
方法,它可以rstrip()
兩側的空格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.