`
54yuri
  • 浏览: 28230 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

a py to delete the trailling spaces and replace the "\t" with 4 spaces

阅读更多
#author: 54yuri

import os
import sys


def read_file( file_path ):
    fd = open( file_path, "r" )
    fd.seek( 0, os.SEEK_SET )
    content = fd.read()
    fd.close()
    
    return content
    
def write_file( file_path, content ):
    fd = open( file_path, "w" )

    fd.seek( 0, os.SEEK_SET )
    fd.write( content )
    fd.flush()
    fd.close()


def trim_trailling_spaces( old_content ):
    new_content = ""
    for line in old_content.splitlines():
        line = line.rstrip(" ")
        new_content += ( line + "\n" )

    return new_content

def replace_tab_sign_with_spaces( old_content ):
    new_content = ""
    for line in old_content.splitlines():
        line = line.replace( "\t", "    " )
        new_content += ( line + "\n" )
    return new_content


def open_files( base_dir, file_ext_name ):
    
    content = ""
    for root, dirs, files in os.walk( base_dir ):
        for file_name in files:
            #print file_name
            if ( os.path.splitext( file_name )[1] == file_ext_name ):
                file_path = root + "/" + file_name
                content = read_file( file_path )

                print "%s need to be adjusted"%file_path
                content = replace_tab_sign_with_spaces( content )
                content = trim_trailling_spaces( content )

                write_file( file_path, content )


def test1( ):
    base_dir = "/tmp/abc"
    file_ext_name = ".py"
    open_files( base_dir,  file_ext_name )


if __name__ == '__main__':
    test1( ) 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics