06 | Files
Files and Data Review
I mentioned the following on several ocasions, but I don't think I have it in writing, so here it is:
Difference of using open() vs with open()
- if we use
open()
to open a file we must explicitlyclose
an opened file instance, or other parts of the code may face errors while opening the same file. - Using the
with open()
function is an example of a Python context manager.
Using the with open()
context statement makes the code more tidy as we can easily separate between code block by difference in indents. In case of open()
, not closing the file instance, may cause memory leaks and other I/O operation errors.
These example practice files at W3 Schools are good because they introduce all of the file handling basics, but they do use the open and close, which is fine, but it is better to avoid using open and close and instead use the context manager with open()