# Load the source file sourcePath = r'c:\path\to\my\file.cpp' sourceText = codecs.open(sourcePath, encoding='utf-8').read() # Find the generated section startMarker = ( '''/* * Generated data tables - do not edit by hand! * To regenerate, run my_fancy_script.py. */ ''') startMarkerPos = sourceText.index(startMarker) endMarker = ( '''/* * End of generated section */ ''') endMarkerPos = sourceText.index(endMarker) # Rewrite the file with the new generated section, # but only if it's different from the existing one. generatedCodePrev = sourceText[startMarkerPos + len(startMarker) : endMarkerPos] if generatedCode != generatedCodePrev: sourceTextNew = (sourceText[:startMarkerPos] + startMarker + generatedCode + sourceText[endMarkerPos:]) codecs.open(sourcePath, mode='w', encoding='utf-8').write(sourceTextNew) print('Updated %s with new data tables.' % sourcePath) else: print('No changes to %s needed.' % sourcePath)