Tip:
Highlight text to annotate it
X
Hello. My name is Gareth Latty, and in this video, I'm going to talk about working with
files in Python, and more specifically: the 'with' statement.
So we have a small program here, that opens a file, loops through each line, makes an
integer from that line, and prints out the value. As you can see, you get the expected
result.
However, whenever we are working with files, we should always close the files, as it ensures
system resources get freed up.
Now we can see that our file is getting closed at the end of execution. This is fine, however,
we are also missing another potential bug. What happens if there is an exception during
execution?
We have some bad data here, where one of the values isn't a number. Now we can deal with
this: we just want to stop execution, so we wrap this to catch the exception.
Now when we run it, we can see it just stops at the second line - which is the last good
line. However, there is another problem. The file is not being closed. This is because
file.close() never gets reached when the exception is thrown. To get around this bug, we could
just re-order our code. However, the more complex the code gets, the harder this is
going to be to do right, and what we really want to do is to say this always gets run
in the end.
Fortunately, we have a way of doing that - and that's the finally block, so if we wrap this…
we can see that the file gets closed, even though there is an exception, because the
finally block ensures it gets run.
Ideally, we want to do this every time we work with a file. However, that quickly becomes
very repetitive - rewriting the same code every time. Fortunately, ever since Python
2.5, we have a way to deal with this automatically - and that's called the 'with' statement,
and context managers.
Every file is a context manager, and that allows us to let Python deal with closing
the file, and ensuring that that always gets run. So how do they work?
As you can see here, we use the 'with' statement and say we want to open this file, then we
give it the name to assign that file to. The 'with' statement will automatically close
the file when the block is exited. So you can see, by the time it reaches this statement
here, the file has been closed.
So, what happens if there is an exception like before?
If we catch that exception… You can see that this line gets run, because the file
is closed. As soon as the 'with' block is exited, that file gets closed.
You can see here that the 'with' statement is a powerful tool, that allows you to write
clear, concise, and effective code, without having to repeat yourself. I would always
recommend using the 'with' statement, wherever you are dealing with files, as there is no
downside, and there is a benefit to always doing it right.
Thanks for watching.