class UtilException(Exception): pass def bulk_replace(filepath, pattern, replace_with, line=None): """ Function which open file, find necessary pattern and replace it with new fragment. :param filepath: Path to file :param pattern: String to replace :param replace_with: The new string to replace with :param line: In which line in the file to replace (if empty, then replace all) :return: """ try: assert pattern != replace_with except AssertionError: raise UtilException('pattern and replace_with can not be same') with open(filepath, 'r') as f: text = f.readlines() f.close() if line: # assume we get line number, not index try: assert line >= 1 try: # replace necessary text text[line-1] = text[line-1].replace(pattern, replace_with) _write_lines(filepath, text) except IndexError: raise UtilException('line not found') except AssertionError: raise UtilException('line index should be gte 1') else: # walk through all lines and replace necessary text lines = [line.replace(pattern, replace_with) for line in text] _write_lines(filepath, lines) def _write_lines(filepath, lines): """ Helper function :param filepath: File path to open :param lines: list of lines :return: """ with open(filepath, 'w') as f: f.writelines(lines) f.close()