Sep-16-2019, 06:46 AM
(Sep-16-2019, 06:09 AM)perfringo Wrote:(Sep-16-2019, 05:23 AM)YoungGrassHopper Wrote: Oh wow I did not know there is an alternative way to open files, and I was explicitly told to please remember to close them in order to free up the resources they used or something like that, I will look into your method , thanks for the advice and the fix on the code runs like a charm now with no hassle. Much appreciate perfringo
From Documentation >>> The Python Tutorial >>> 7. Input and Output >>> 7.2. Reading and Writing Files
Quote:It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.
/.../
If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it. If you don’t explicitly close a file, Python’s garbage collector will eventually destroy the object and close the open file for you, but the file may stay open for a while. Another risk is that different Python implementations will do this clean-up at different times.
One reason why 'with' is better: while writing the code it can contain errors and blow up. If this happens in code block after open() but before close() this means that file stays open. Some unexpected behaviour can be expected if files are not properly closed (especially if you blow up code again and again). 'with' ensures that file is always closed whatever happens.
This is mighty interesting, thanks for the advice perfringo I will try incorporate this "with" method when opening files from now on and refrain from using the other one in the future. sounds more efficient and safe