繁体   English   中英

如果之前有空格,如何在python中查找和添加新行

[英]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")

lstrip()方法将删除字符串开头的前导空格、换行符和制表符:

>>> '     hello world!'.lstrip()
'hello world!

参考: 如何删除 Python 中的前导空格?

改变这个

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM