#小练习 替换文件某行内容

来源:互联网 发布:秦时明月 知乎 编辑:程序博客网 时间:2024/06/11 06:03
import fileinput
s='''
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
Last line
'''
f=open(r'G:\\13.txt','w')
f.write(s)
f.flush()
f.close()

f=fileinput.input(r'G:\\13.txt',inplace=1,backup='.bak')

for i  in f:
    if 'fun' in i:
        i=i.replace('fun','Fun')
    print i,

f.close()


也可以使用re.sub()对文件进行替换:

f=fileinput.input(r'G:\\13.txt',inplace=1,backup='.bak')

for i  in f:

    p='fun'

    if 'fun' in i:
        i=re.sub(p,'FUN',i)
    print i,

f.close()


原创粉丝点击