Use the 'with' statement to open files, which will automatically close the file when it goes out of scope.

  • Avoid using file handlers altogether
  • Depend on the operating system to close it
  • Manually close the file at the end of script
  • Use 'finally' block to close the file
Using the 'with' statement ensures that the file is automatically closed when it's no longer needed, preventing resource leakage.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *