Python Cookbook学习记录 ch2_3_2013/10/27

2.3搜索和替换文件中的文本

需要将文件中的某个字符串改变成另外一个。

字符串中replace方法提供了字符串替换最简单的办法:

>>> s = 'hello world'
>>> s.replace('l','L')
'heLLo worLd'

搜索替换需要两个文件,先第一个文件,再通过replace方法将里面的内容进行铁环,再讲替换完的内容输入到另外一个文件中

>>> file_object = open('thefile.txt')
>>> file_to = open('abinfile')
>>> list_of_all_the_lines = file_object.readlines()
>>> file_to = open('abinfile','w')
>>> for item in list_of_all_the_lines:
    item = item.rstrip()
    file_to.write(item.replace('l','L'))

    
>>> file_to.close()
>>> file_object.close()

 

posted on 2013-10-27 17:42  七海之风  阅读(131)  评论(0)    收藏  举报

导航