zoukankan      html  css  js  c++  java
  • 替换文本内容

    一个简单的例子,查看当前文件路径中的文件,查找有‘bye’字符的行,并修改为‘bye’。

    注:  else:

                file_out.write(line)

    这两行代码不能少,保证了没有包含‘bye’字符的行也可以被重新写入文件中,防止了处理完成后文件中只剩下字符所在行。

    #!/usr/bin/python
    
    import os
    
    def chtext(filename):
    
        file_handle = open(filename,'r')
    
        lines = file_handle.readlines()
    
        file_handle.close()
    
        file_out = open(filename,'w')
    
        for line in lines:
    
            if not line:
    
                break
    
            if 'bye' in line:
    
                file_out.write(line.replace('bye','bye'))
    
            else:
    
                file_out.write(line)
    
        file_out.close()
    
    def chkname():
    
        path=os.path.abspath(".")
    
        print("path is %s" %(path))
    
        filelist = os.listdir(path)
    
        for root,dirname,filename in os.walk(path):
    
            for f in filename:
    
                print("name is: %s" %f)
    
                chtext(os.path.join(root,f))
    
     
    
       #      object_handle = open(files)
    
    #        file_text = object_handle.read()
    
    #        print(" %s" %(file_text))
    
    #        object_handle.close()
    
    chkname()
  • 相关阅读:
    暑假自学(19)
    暑假自学(18)
    暑假自学(17)
    暑假自学(16)
    暑假自学(15)
    rsync简介
    10.Go语言-面向对象简单了解
    dp 数字三角形
    P1359租用游艇(dp+dfs)
    油田问题 bfs
  • 原文地址:https://www.cnblogs.com/edver/p/7154665.html
Copyright © 2011-2022 走看看