Python with statement is used with try/finally statements. It is used with unmanaged resources (like file streams). The
with the statement clarifies code that previously would use
try...finally blocks to ensure that clean-up code is executed.
with expression [as variable]: with-block
Example “with statement” in Python
Simple example code using “with statement”.
In the normal file operation, we have to follow some rules, like opening the file using ‘open()’ method then read the file data using ‘read()’ method after that print the data of file and when all operation gets over we need to close the file using ‘close()’ method.
Using the “With-statement”, we can get automatic exception handling and better syntax.
Example: Writing file
with open('file_path', 'w') as file: file.write('Hello world !')
with open('file.txt') as infile: for line in infile: print(line)
Hello world, python programming.
Do comment if you have any doubts and suggestions on this Python keyword tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.