2017-06-22 53 views
1

據我所知,這可能適用於一種情況,但它會清除我的文件並替換文件中的查找字符串。如何一次找到並替換文件中的不同字符串?

#!/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 
+0

你是你'else' statment後失蹤了'write',所以未改變線路不讓它回到您的文件。另外,在你的第一個'elif'中,你有'print lin'而不是'print line'。 –

+0

你不使用XML解析器並使用其功能來查找和編輯元素的任何原因? –

+0

請修復您的縮進。 – SiHa

回答

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() 
+0

這是工作代碼來替換文件中的字符串。 – manjunath

相關問題