python写一段脚本代码自动完成输入(目录下的所有)文件的数据替换(修改数据和替换数据都是输入的)【转】

转自:http://blog.csdn.net/lixiaojie1012/article/details/23628129

 
 在CODE上查看代码片派生到我的代码片
  1. 初次尝试python语言,感觉用着真舒服,简单明了,库函数一调用就OK了
    
    [python] view plain copy 在CODE上查看代码片派生到我的代码片
    import sys,os,os.path  
    def file_replace():  
        path = sys.argv[1]  
        old_data = sys.argv[2]  
        new_data = sys.argv[3]  
        if not os.path.exists(path):  
            print 'file of dir does not exists!\n'  
            return  
        elif os.path.isdir(path):     
            for root,dirs,files in os.walk(path):  
                for fn in files:  
                    filepath = os.path.join(root,fn)  
                    f = open(filepath,'r+')  
                    line = f.readlines()  
                    f.seek(0)  
                    for s in line:  
                        f.write(s.replace(old_data,new_data))  
                    f.close()  
        elif os.path.isfile(path):  
            f = open(path,'r+')  
            line = f.readlines()  
            f.seek(0)  
            for s in line:  
                f.write(s.replace(old_data,new_data))  
            f.close()  
        else:  
            print 'argv[1] illegal,not a file or dir\n'  
            return  
    if __name__=='__main__':  
        file_replace()  

     

posted @ 2016-03-29 17:04  Sky&Zhang  阅读(613)  评论(0编辑  收藏  举报