Skip to content

With keyword in Python

  • by

Use With keyword/statement to simplify exception handling in Python. It is used in exception handling to make the code cleaner and much more readable.

# without using with statement
file = open('file-path', 'w')
try:
    file.write('Loremipsum')
finally:
    file.close()

# with statement
with open('file-path', 'w') as file:
    file.write('Loremipsum')

With keywords in Python

A simple example code shows the tryfinally approach to file stream resource management.

# without using with statement
file = open('hello.txt', 'w')
try:
    file.write('Loremipsum 1')
finally:
    file.close()

# with statement
with open('hello.txt', 'w') as file:
    file.write('Loremipsum 2')

Output:

With keywords in Python

Do comment if you have any doubts or suggestions on this Python keyword topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading