zoukankan      html  css  js  c++  java
  • #小练习 替换文件某行内容 分类: python 小练习 python Module 2013-09-26 11:10 269人阅读 评论(0) 收藏

    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()


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    初识MySQL
    正则表达式
    多线程
    多进程
    Python基础--模块
    Python基础--异常
    Python基础--面向对象
    Python基础--文件操作
    Python基础--函数
    python3 日期时间差计算
  • 原文地址:https://www.cnblogs.com/think1988/p/4628057.html
Copyright © 2011-2022 走看看