2017-06-22 5 views
1

私の知る限り、これは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'なステートメントの後に' write'含まれていないので、非変更された行が戻ってあなたのファイルにそれをしません。また、最初の 'elif'では' print line'の代わりに 'print lin'があります。 –

+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

関連する問題