Python 如何一次查找和替换文件中的不同字符串?

Python 如何一次查找和替换文件中的不同字符串?,python,Python,据我所知,这可能适用于一种情况,但它会清除我的文件并替换文件中的查找字符串 #!/usr/bin/python open('vpc.xml','r+') as p: #open a file in read and write mode p=rp.readlines() print p #printing what content read by p for line in p: #for loop up to end of line in file

据我所知,这可能适用于一种情况,但它会清除我的文件并替换文件中的查找字符串

 #!/usr/bin/python
    open('vpc.xml','r+') as p: #open a file in read and write mode
    p=rp.readlines()
    print p #printing what content read by p
    for line in p: #for loop up to end of line in file
          if "<mac address=" in  line: #if condition encounter by for loop line then it replaces the string specified in if condition.
             print line
             r.write(line.replace("<mac address=","<mac address1="))
           elif "<source bridge=" in line:
             print line
             r.write(line.replace("<source bridge=","<source bridge1="))
           elif "<target dev" in line:
                 print line
                 r.write(line.replace("<target dev","<target dev1"))
           else :
             print 'no changes'
             continue
#/usr/bin/python
打开('vpc.xml','r+')作为p:#以读写模式打开文件
p=rp.readlines()
打印p#打印p读取的内容
对于p中的行:#对于循环,直到文件中的行结束
如果“
!/usr/bin/python
o=输入(“输入VPC数量”)
y=输入(“输入eth接口的数量”)
对于范围(1,o)内的k:
h='vpc'+str(k)+'.xml'
打印h
#j=输入(“输入eth接口的数量”)
ri=开启(h,'r')
line=ri.read()
ri.close()
对于范围(0,y)中的i
适用于范围(i+1)内的s
dev_val={'network':'bridge','
#!/usr/bin/python
o=输入(“输入VPC数量”)
y=输入(“输入eth接口的数量”)
对于范围(1,o)内的k:
h='vpc'+str(k)+'.xml'
打印h
#j=输入(“输入eth接口的数量”)
ri=开启(h,'r')
line=ri.read()
ri.close()
对于范围(0,y)中的i
适用于范围(i+1)内的s

德夫瓦尔={'network':'bridge','You's missing the
write
在您的
else
声明之后,因此未更改的行不会返回到您的文件中。此外,在您的第一个
elif
中,您有一个
打印行而不是
打印行
。您没有使用XML解析器并使用其功能查找和编辑任何原因元素?请修复缩进。是否在
open()中缺少带有
line?另外,
r
是如何定义的?p、r和rp的组合缺乏一致性…你在
else
station之后缺少
write
,因此未更改的行不会回到你的文件中。另外,在你的第一个
elif
,你有一个
print lin
,而不是
print line
。一个您不使用XML解析器并使用其功能查找和编辑元素的原因是什么?请修复缩进。您是否在
open()
行中缺少
with
?另外,
r
是如何定义的?您的p、r和rp混合使用,缺乏一致性。。。
#!/usr/bin/python
o = input("enter how many vpcs")
y = input("enter how many eth interfaces")
for k in range(1,o):
        h='vpc'+str(k)+'.xml'
        print h
#j = input("enter how many eth interfaces")
        ri=open(h,'r')
        line = ri.read()
        ri.close()
        for i in range(0,y)
                for s in range(i+1)
        dev_val={'network':'bridge','<man':'<manneth0','<man':'vpc'+str(i)+_eth+str(i),}
                for key,val in dev_val.items():
                                line = line.replace(key,val)
                                print line
                with open(h,'w') as v:
                        v.write(line)
                        v.close()