python替换文件指定字符串

需求:将文件中的全部he替换成s


with open('/download/python_practice/a.py','r') as r:

    lines=r.readlines()
with open('/download/python_practice/a.py','w') as w:
    for l in lines:

        w.write(l.replace('he','s'))


--如若想替换某行的某个内容,需要加个if判断(注意,必须要写else,否则write替换后的行内容会完全覆盖文件之前的所有内容):

--替换以PATH开头的那一行的内容:/usr/local/mysql/bin为空

[root@PC python_practice]# cat g.py
with open('/download/python_practice/d.py','r') as r:
    lines=r.readlines()
with open('/download/python_practice/d.py','w') as w:
    for l in lines:
       if l.startswith('PATH'):
           w.write(l.replace(':/usr/local/mysql/bin',''))
       else:
           w.write(l)


你可能感兴趣的:(python替换文件指定字符串)