python文本内容替换?

Python013

python文本内容替换?,第1张

这样编写:

fa=open("A.txt","r")

ta=fa.readlines()

fb=open("B.txt","r")

tb=fb.readlines()

tb[2:-9]=ta

fa.close()

fb.close()

fb=open("B.txt","w")

fb.writelines(tb)

fb.close()

1、说明

可以使用find或者index来查询字符串,可以使用replace函数来替换字符串。

2、示例

1)查询

>>>'abcdefg'.find('cde')

结果为2

'abcdefg'.find('acde')

结果为-1

'abcdefg'.index('cde')

结果为2

2)替换

'abcdefg'.replace('abc','cde')

结果为'cdedefg'

3、函数说明

1)find(...)

S.find(sub[, start[, end]]) ->int

返回S中找到substring sub的最低索引,使得sub包含在S [start:end]中。 可选的 参数start和end解释为切片表示法。

失败时返回-1。

2)index(...)

S.index(sub[, start[, end]]) ->int

与find函数类似,但是当未找到子字符串时引发ValueError。

3)replace(...)

S.replace(old, new[, count]) ->str

返回S的所有出现的子串的副本旧换新。 如果可选参数计数为给定,只有第一个计数出现被替换。

a_lines = open('a.txt') #192.168.1.0 usage 90%

a_ = a_lines.readlines()

b_lines = open('b.txt') #192.168.1.0 LAN-User ,192.168.2.0 Wireless-User

b_ = b_lines.readlines()            

c_lines = open('c.txt','wb')

for i in b_:

    tmp = i.strip().split()[0]#得到192.168.1.0

    for j in a_:

        tmp1 = j.strip().split()

        if tmp == tmp1[0]:

            tmp2= i.strip()+j.strip().replace(tmp1[0],'')+'\r\n'

            c_lines.write(tmp2)

a_lines.close()

b_lines.close()

c_lines.close()