🛠️ Scheduled Maintenance | We’ll be undergoing scheduled maintenance and upgrades between 00:00 PST Jan 26th until 00:00 PST Jan 28th. There may be brief interruption of services in that period. We apologize for the inconvenience.

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.
Anybody can ask a question
Anybody can answer
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


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

1 Answer


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:

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.
365 Team

Thanks. I am clear now

8 months