How is the ‘with’ statement used in python?. Especially, when used in the opening of a file in the web scrapping lecture.
The ‘with’ statement in Python is a shorthand for a “try-finally” block.
So, what is a “try-finally” block?
Well, imagine you need to do some stuff with a file. You first need to open it, preocess it and then close it.
What happens, though, if something goes wrong when processing the file? The program would stop.
The important bit is that the program would crash before the file has been closed. In the past, that could have led to serious damage.
Nowadays, modern systems can cope with this problem, but it can still produce bugs.
So, a “try-finally” block was implemented into the language.
Here is a sample code:
file = open(...)
# process the file
In this way, whatever is in the “try” part would get executed first. However, independend of any problems in the “try” part, the “finally” block will always run. No matter if there was an error in the code in the “try” part, teh file would always be closed.
This had to always be written when dealing with files. In order to make the code easier to write, the developers of Python 3 created the “with” keyword.
It basically does the same thing as try-finally. When you open a file using “with”, it will always be closed at the end.
Thanks. I am clear now