What will happen if I do not close a file in python programming after opening it and I run the programme? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What will happen if I do not close a file in python programming after opening it and I run the programme?

I see there was no compilation or run time error. Then why all suggest to close the file after using it in python programming?

11th Jan 2019, 1:57 PM
Jyotiprakash Das Karmakar
Jyotiprakash Das Karmakar - avatar
2 Answers
+ 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.
11th Jan 2019, 2:12 PM
Hatsy Rei
Hatsy Rei - avatar
+ 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.
11th Jan 2019, 2:31 PM
Anna
Anna - avatar