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

时间:2022-08-28 19:34:26

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

  1. 初次尝试python语言,感觉用着真舒服,简单明了,库函数一调用就OK了
    
    [python] view plain copy 在CODE上查看代码片派生到我的代码片
    import sys,os,os.path
    def file_replace():
    path = sys.argv[]
    old_data = sys.argv[]
    new_data = sys.argv[]
    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()
    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()
    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()