In this Tutorial :-

Pre-requisite: File Handling in Python
What is with statement ?
The with statement in Python can be used to open a file in any of the valid opening modes.
Advantage of using ‘with’ statement is that it will take care of closing a file which it opened. Hence, we need not to write file.close() in order to close a file.
Even in the case of an exception, with statement in Python will close the file before the exception is handled.
Syntax
with open(filename, opening_mode) as fileobject:

Code Example
To open a file in python using with statement.
with open('sample.txt', 'r') as f:
for row in f:
print(row)
O/P
Hello World
That’s all in ‘with statement in Python’.

Thx