4 Antworten
+ 4
When you open a file in Python, or using any language for that matter, you are basically starting a process which requests and holds on to a resource file. Before the file is released, no other processes are allowed to access that file you requested. If your program/script is relatively short, it doesn't matter since the resource is released once the process ends. However, if your process continues running after you've completed your work with that file, you would have a case of resource hogging if you do not release/close the file handler - and that's only the start. What happens if, your process crashes unexpectedly while the file is open? Did you handle the exception by closing the file before killing the process? Such caution is required when dealing with external resources such as files.
+ 3
I don't think any programming language will give you a compilation or runtime error for not closing a file. It's your job as a programmer to make sure that all files are closed when you don't need them any longer. Btw, the recommended way to deal with files in python is to use a context manager like this:
with open('file', 'wt') as f:
# do something
This will close the file automatically for you, even in case of an exception. No f.close() needed.