python 替换xml中的一行或者两行

Python030

python 替换xml中的一行或者两行,第1张

a='<Range>0-229956 </Range>'

b="'<Range>0-(A-1) </Range>'\n'<Range>B-229956 </Range>'"

d=open("a.xml","w")

while 1:

line=d.readline()

if line==a:

replace(a,b)

ifnotline:

break

##如果你的A,B两个值是从终端读取的话在开始read一下就行:

read A

read B

#coding=utf-8

'''

Created on 2014-11-20

@author: Neo

'''

todo = {

    10: {'AAAA': '1.1.1.1'},

    20: {'BBBB': 'bbbbb'},

    30: {'#': ''},

    }

fp = open('test.txt')

data = ''

i = 0

for line in fp.readlines():

    i += 1    

    if i in todo.keys():

        print 'line', i, line

        for key in todo[i]:

            line = line.replace(key, todo[i][key])

        print 'after replace:', line

    data += line

fp.close()

#保存在另一个文件

ret = open('result.txt','w+')

ret.write(data)

ret.close()

result:

line 10 AAAA

after replace: 1.1.1.1

line 20 BBBB

after replace: bbbbb

line 30 A##AA####A

after replace: AAAA

ls1=open("f1.txt").readlines()

ls2=open("f2.txt").readlines()

at=20

ls1[at]=ls2[at]

f=open("f3.txt","w")

for l in ls1:

    f.write(l)

f.close()