import re with open('index.php', 'r') as f: content = f.read() patch_code = """ instanceModalElement.addEventListener('hidden.bs.modal', function () { if (window.matrixNeedsRefresh) { window.location.reload(); } }); }); """ content = content.replace("});\n", patch_code) with open('index.php', 'w') as f: f.write(content) print("Patched index.php")