1. Not Using with
to Open Files
When you open a file without the with
statement, you need to remember closing the file via calling close()
explicitly when finished with processing it. Even while explicitly closing the resource, there are chances of exceptions before the resource is actually released. This can cause inconsistencies, or lead the file to be corrupted. Opening a file via with
implements the context manager protocol that releases the resource when execution is outside of the with
block.
Bad practice: