try: requirements = open("requirements.txt", "w") requirements.write( "scikit-learn >= 0.24.2, < 0.25.0", "numpy >= 1.21.2, < 1.22.0", "pandas >= 1.3.3, < 1.4.0" ) random_error = 25 / 0 # raises a 0 divide exception requirements.close() # this is skipped except: print("An error occurred.")