The 365 Data Science team is proud to invite you to our own community forum. A very well built system to support your queries, questions and give the chance to show your knowledge and help others in their path of becoming Data Science specialists.
Ask
Anybody can ask a question
Answer
Anybody can answer
Vote
The best answers are voted up and moderated by our team

How to use ‘with’ statement in python

How to use ‘with’ statement in python

0
Votes
1
Answer

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

1 Answer

0
Votes

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

Thanks. I am clear now

4 months
×
LAST CHANCE
Ready to Learn Data Science?
50% OFF