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

2024-04-26 01:33:30 发布

您现在位置: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

Tags: 文件insourcetargetforreadbyif
1条回答
网友
1楼 · 发布于 2024-04-26 01:33:30
#!/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()

相关问题 更多 >