Last answered:

19 May 2020

Posted on:

15 May 2020

0

How to use ‘with’ statement in python

How is the 'with' statement used in python?. Especially, when used in the opening of a file in the web scrapping lecture.

1 answers ( 0 marked as helpful)
Instructor
Posted on:

19 May 2020

0
Dear Mark, 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:
try:
file = open(...)
# process the file
finally:
file.close
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.   Best, 365 Team

Submit an answer