#!/usr/bin/env python import sys,os,shutil #----------------------------------------------------------------------- def replace_string(file,oldstr,newstr): # # Replace all occurrences of "oldstr" in oldfile to "newstr" in newfile. # Note oldfile and newfile may be the same, i.e., overwrite oldfile. # # Read contents first, then close input file. # file_read = open(file,'r') contents = file_read.read() file_read.close() # print contents # # Open output file and change chars per line. # fw = open(file,'w') for line in contents: newline = line.replace(oldstr,newstr) fw.write(newline) fw.close() #----------------------------------------------------------------------- # oldstr = ';' newstr = '!' for file in sys.argv[1:]: # print 'file = ',file,': Changing "',oldstr,'" to ',newstr if os.path.isfile(file): answer = raw_input('Overwrite file '+file+' (y/n/q, default=n)? ') if answer == 'q': sys.exit() if answer == 'y': replace_string(file,oldstr,newstr) print 'Overwrote file ',file,' with "',oldstr,'" replaced by "',newstr,'"' elif answer == 'n' or answer == '': newfile = file+'.new' shutil.copyfile(file,newfile) replace_string(newfile,oldstr,newstr) print 'Wrote file ',newfile,' with "',oldstr,'" replaced by "',newstr,'"' else: print 'File ',file,' is unchanged.' else: print '>>> Cannot find file ',file continue