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

时间:2017-06-22 10:05:17

标签: 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
          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

1 个答案:

答案 0 :(得分:0)

#!/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()