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.
00:01
First, opening and closing files in Python. Files are opened with the open()
statement, which takes a filename or path as its argument, as seen here onscreen.
00:15
Files should always be closed after use, using the .close()
method, as seen here. Let’s look at opening and closing a file.
00:26
As you can see here, the file object is created using open()
and the filename, as previously seen.
00:34
This creates a file
object which has methods attached to it, but the most important one for us right now is the .close()
method, which we’re going to use to close the file without doing anything else.
00:45
The file is safely closed and we can move on. Ensuring that a file is closed when an error occurred can be done a couple of ways. One of them is using a try
and finally
block, as seen here, where the finally
block includes the .close()
method to ensure the file is closed regardless of what occurs.
01:05
Another way to ensure that a file is closed regardless of whether an error occurs is to use the with
context manager, as seen here. The open()
statement follows with
and creates a context where the file is open.
01:21 Once that context is complete and the code is no longer indented, the file is automatically closed, ensuring that it will not be left open. This is a method you’ll see in action throughout the rest of these videos.
Become a Member to join the conversation.