import os import re with open('core/views.py', 'r') as f: content = f.read() # Find the first occurrence of return render(request, 'core/log_door_visit.html', context) # and the next def door_visit_history(request): pattern = r"(return render\(request, 'core/log_door_visit.html', context\)).*?(def door_visit_history\(request\):)" new_content = re.sub(pattern, r"\1\n\n\2", content, flags=re.DOTALL) with open('core/views.py', 'w') as f: f.write(new_content)