def set_constant(file, constant, value, comment = ''): ''' Search through file for the constant and either adds it to the end or updates the existing value. Comment is optionally passed and is placed on the same line as the constant along with the modification date/time. Comment is only updated if the value is updated. It's recommended that the file for local_constants.py be different than the file checked into your repo as it's locally maintained. Example: set_constant('a.txt', 'TYPE', 1, 'This is optional') Author: Ed Menendez (ed@menendez.com) ''' write_file = found_constant = False if comment: comment += ' ' line_to_write = '%s = %s # %sLast modified %s\n' % \ (constant, value.__repr__(), comment, datetime.datetime.now()) # The file to be written is stored here. new_file = '' try: f = open(file, 'r+') except IOError: # Nothing to search through here. Move along. f = None else: # Loop through the file and look for the string for line in f.readlines(): if line.find(constant) > -1: line_splits = line.split('=') if len(line_splits) == 2: # Yes, it's an assignment line. old_constant, old_value = line_splits old_constant = old_constant.strip() if old_constant == constant: # We've found the contant! found_constant = True old_value_splits = old_value.split('#') if len(old_value_splits) == 2: old_value, trash = old_value_splits else: old_value = old_value_splits[0] old_value = old_value.strip() if old_value != value.__repr__(): # It's changed! write_file = True line = line_to_write new_file += line f.close() # If nothing found, then add it to the end if not found_constant: write_file = True # New line needs to be added in case the file doesn't end with a new # line. Could be made smarter and check for the newline. This will make # for a prettier local_constants.py new_file += '\n' + line_to_write if write_file: # Write out the new file f = open(file, 'w+') f.write(new_file) f.close()