Opening and Closing Files
In this lesson, you’ll learn about how to open and close files in Python. When you want to work with a file, the first thing to do is to open it. This is done by invoking the
open() built-in function.
open() has a single return: the file object.
It’s important to remember that it’s your responsibility to close the file. In most cases, upon termination of an application or script, a file will be closed eventually. However, there is no guarantee when exactly that will happen.
This can lead to unwanted behavior including resource leaks. It’s also a best practice within Python (Pythonic) to make sure that your code behaves in a way that is well defined and reduces any unwanted behavior.
Comments & Discussion
Become a Member to join the conversation.